Flatten list column in data frame with ID column

前端 未结 4 517
逝去的感伤
逝去的感伤 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:39

    Using base R, one option is stack after naming the list elements of 'b' column with that of the elements of 'a'. We can use setNames to change the names.

    stack(setNames(df$b, df$a))
    

    Or another option would be to use unstack to automatically name the list element of 'b' with 'a' elements and then do the stack to get a data.frame output.

    stack(unstack(df, b~a))
    

    Or we can use a convenient function listCol_l from splitstackshape to convert the list to data.frame.

    library(splitstackshape)
    listCol_l(df, 'b')
    

提交回复
热议问题