library(stringr)
library(dplyr)
have %>% tbl_df %>% group_by(ID) %>% summarise_each(funs(str_c(., collapse="; ")))
Edit 1: So tbl_df
may not needed and instead of the str_c of the stringr
package you could use paste
(in base
). And what the above does is to group by the ID column and then apply the str_c
(or paste
) function to each remaining column for each group.
Edit 2: Another solution using the data.table package:
library(data.table)
dtbl <- as.data.table(have)
dtbl[,lapply(.SD, function(x) paste(x,collapse=";")), by=ID]
The above may be faster, especially if you set the key:
setkey(dtbl, ID)
"Hybrid" solution: You can use the dplyr
syntax for data.tables! For example:
dtbl %>% tbl_dt %>%
group_by(ID) %>%
summarise_each(funs(paste(., collapse="; ")))