Flattening a delimited composite column

后端 未结 3 897
一整个雨季
一整个雨季 2020-12-07 06:01

I got a data frame in R where one of the fields is composite (delimited). Here\'s an example of what I got:

users=c(1,2,3)
items=c(\"23 77 49\", \"10 18 28\"         


        
3条回答
  •  无人及你
    2020-12-07 06:50

    Here is a dplyr solution

    users=c(1,2,3)
    items=c("23 77 49", "10 18 28", "20 31 84")
    df = data.frame(users,items,stringsAsFactors=FALSE)
    rbind_all(do(df %.% group_by(users), 
              .f = function(d) data.frame(d[,1,drop=FALSE], 
                  items = unlist(strsplit(d[['items']],' ')), 
               stringsAsFactors=FALSE)))
    

    It would be really nice to have an expand function, i.e. the opposite of summarise

    eg. if the following would work.

    df %.% group_by(users) %.% expand(unlist(strsplit(items,' ')))
    

提交回复
热议问题