2012-07-10 105 views
2

我有一个数据框,带有两个Id变量和一个名称变量。 这些变量有各种不同数量的组合。组合数据帧的行

## 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 

我想,这样的结果具有每V1只有一个条目,然后值作为第二和第三varaibles逗号分隔列表的行结合起来。像这样:

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 

我已经试过这与下面的代码,这是好的,如果有点慢。任何关于更快解决方案的建议?

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 

编辑:纠正dput(DF)

+0

看起来你'dput “编辑你想要的结果,而不是要转换的数据。 – 2012-07-10 15:37:40

+0

对不起。现在应该修复 – 2012-07-10 15:52:54

+0

速度是你追求的唯一目标?通过将所有这些值合并为单个字符串,您的输出也会将数据限制在一定程度上。使用'聚合'避免了这一点;输出中的每一列都是一个列表,您可以从中轻松恢复到早期的数据格式。 – A5C1D2H2I1M1N2O1R2T1 2012-07-10 16:37:05

回答

3

确保V3(或其他因素的变量)在模式as.character和使用aggregate

df$V3 = as.character(df$V3) 
aggregate(df[-1], by=list(df$V1), c, simplify=FALSE) 
# Group.1   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 
0
do.call("rbind", lapply(split(df[, 2:3], df[,1]), function(x) sapply(x, paste, collapse=","))) 
    V2  V3      
A "1,3,1,1" "test1,test3,test1,test1" 
B "2,2,2,1" "test2,test2,test2,test1" 
C "3,2,1,3" "test3,test2,test1,test3" 
D "1,1,3,1" "test1,test1,test3,test1" 
E "2,3,2,1" "test2,test3,test2,test1"