r - aggregate data.frame with list column -


there 1 column contains vectors in each row of data.frame. aggregate , combine vectors. however, seems cannot this kind of data. how combine vectors?

"error: invalid type (list) variable 'dv'"

#problem: aggregate data.frame list-column  #reproducible code set.seed(1) some_list <- replicate(40, sample(c(1:8), size=sample(1:6, 1), replace=true)) exdf <- expand.grid(id=c(1:10), content=c(1:4)) exdf$dv <- some_list   #this throws error aggregate( formula=dv~id, data=exdf, fun=c ) 

you can use dplyr summarize unlist , list:

library(dplyr) df1 <- exdf %>% group_by(id) %>% summarise(dv = list(unlist(dv)))   df1 # source: local data frame [10 x 2]  #      id         dv #   <int>     <list> #1      1 <int [13]> #2      2 <int [15]> #3      3 <int [13]> #4      4 <int [15]> #5      5 <int [13]> #6      6 <int [15]> #7      7 <int [13]> #8      8 <int [15]> #9      9 <int [13]> #10    10 <int [15]>  df1$dv[[1]] # [1] 3 5 2 6 4 7 8 2 6 2 7 3 4 

or alternatively data.table:

library(data.table) setdt(exdf)[, .(list(unlist(dv))), id]  #    id           v1 # 1:  1 3,5,2,6,4,7, # 2:  2 2,8,8,6,6,1, # 3:  3 2,6,4,7,8,2, # 4:  4 7,4,6,4,1,4, # 5:  5 4,7,8,2,6,2, # 6:  6 4,1,4,2,7,6, # 7:  7 7,3,4,3,5,2, # 8:  8 4,2,7,6,2,8, # 9:  9 3,5,2,6,4,7, #10: 10 2,8,8,6,6,1, 

Comments

Popular posts from this blog

mongodb - How to keep track of users making Stripe Payments -

javascript - Fire on return from form "Submit" -

javascript - Thinglink image not visible until browser resize -