Flatten list column in data frame with ID column

前端 未结 4 569
逝去的感伤
逝去的感伤 2021-01-17 11:16

My data frame contains the output of a survey with a select multiple question type. Some cells have multiple values.

df <- data.frame(a=1:3,b=I(list(1,1:2         


        
4条回答
  •  自闭症患者
    2021-01-17 11:52

    Here's another base solution, far less elegant than any other solution posted thus far. Posting for the sake of completeness, though personally I would recommend akrun's base solution.

    with(df, cbind(a = rep(a, sapply(b, length)), b = do.call(c, b)))
    

    This constructs the first column as the elements of a, where each is repeated to match the length of the corresponding list item from b. The second column is b "flattened" using do.call() with c().

    As Ananda Mahto pointed out in a comment, sapply(b, length) can be replaced with lengths(b) in the most recent version of R (3.2, if I'm not mistaken).

提交回复
热议问题