I have a data frame with an two Id variables and a name variable.
There are various unequal numbers of combinations of these variables.
## dput'ed data.frame
df <- structure(list(V1 = structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L,
4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("A",
"B", "C", "D", "E"), class = "factor"), V2 = c(1L, 2L, 3L, 1L,
2L, 3L, 2L, 2L, 1L, 3L, 1L, 2L, 1L, 3L, 2L, 1L, 1L, 3L, 1L, 1L
), V3 = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 2L, 2L, 1L, 3L, 1L,
2L, 1L, 3L, 2L, 1L, 1L, 3L, 1L, 1L), .Label = c("test1", "test2",
"test3"), class = "factor")), .Names = c("V1", "V2", "V3"), class = "data.frame", row.names = c(NA,
-20L))
>df
V1 V2 V3
1 A 1 test1
2 B 2 test2
3 C 3 test3
4 D 1 test1
5 E 2 test2
6 A 3 test3
7 B 2 test2
8 C 2 test2
9 D 1 test1
10 E 3 test3
11 A 1 test1
12 B 2 test2
13 C 1 test1
14 D 3 test3
15 E 2 test2
16 A 1 test1
17 B 1 test1
18 C 3 test3
19 D 1 test1
20 E 1 test1
I want to combine the rows so that the result has only one entry per V1, and then a comma separated list of values as the second and third varaibles. Like so:
f V2 V3
1 A 1 ,3 ,1 ,1 test1 ,test3 ,test1 ,test1
2 B 2 ,2 ,2 ,1 test2 ,test2 ,test2 ,test1
3 C 3 ,2 ,1 ,3 test3 ,test2 ,test1 ,test3
4 D 1 ,1 ,3 ,1 test1 ,test1 ,test3 ,test1
5 E 2 ,3 ,2 ,1 test2 ,test3 ,test2 ,test1
I have tried this with the following code which is fine if a bit slow. Any suggestions for a faster solution?
df = lapply(levels(df$V1), function(f){
cbind(f,
paste(df$V2[df$V1==f],collapse=" ,"),
paste(df$V3[df$V1==f],collapse=" ,"))
})
df = as.data.frame(do.call(rbind, df))
df
Edit: corrected dput(df)
Make sure that
V3(or other factor variables) are in modeas.characterand useaggregate: