在R中取消堆叠数据框

时间:2014-01-17 18:46:20

标签: r dataframe reshape2

我有一个堆叠数据框

a <- c(1,1,1,1,2,2,3,3,3,3,3,4,4,4,4)  
b <- c(200,201,201,200,220,220,200,220,203,204,204,203,220,200,200)  
d <- c(500,500,500,500,500,501,501,501,501,501,502,502,502,502,502)  
f <- c("G","G","M","M", "G","G","M","M","M","G","M","G","M","G","G")  
df <- data.frame(a,d,b,f)

我使用dcast中的reshape2来取消堆叠数据,如下所示

dcast(df,a+d+b ~ f)   
      a     d   b G M  
1     1   500 200 1 1  
2     1   500 201 1 1  
3     2   500 220 1 0  
4     2   501 220 1 0  
5     3   501 200 0 1  
6     3   501 203 0 1  
7     3   501 204 1 0  
8     3   501 220 0 1  
9     3   502 204 0 1  
10    4   502 200 2 0  
11    4   502 203 1 0  
12    4   502 220 0 1

默认为长度,因为我没有放任何聚合函数。但我想要的是

a   d   b col_1 col_2  
1 500 200    G     M  
1 500 201    G     M  
2 500 220    G    NA  
...and so on  

我希望通过为特定f组合转置列a+d+b并将其附加到帧来“扩展”或取消堆叠数据框。是否有一种优雅的方式,而不必循环组合?

编辑:不一定只有2级G&amp; col M中的f。我只想提出col_1 col_2 col_3,这会将每个唯一f组合转换为a+d+b列。我用for循环完成了它;但是如果数据集很大,那就太笨重了。我本来想让代码更快!

1 个答案:

答案 0 :(得分:3)

dcast(df, a+d+b ~ f, fun.aggregate = function(x) as.character(x)[1])
#Using f as value column: use value.var to override.
#   a   d   b    G    M
#1  1 500 200    G    M
#2  1 500 201    G    M
#3  2 500 220    G <NA>
#4  2 501 220    G <NA>
#5  3 501 200 <NA>    M
#6  3 501 203 <NA>    M
#7  3 501 204    G <NA>
#8  3 501 220 <NA>    M
#9  3 502 204 <NA>    M
#10 4 502 200    G <NA>
#11 4 502 203    G <NA>
#12 4 502 220 <NA>    M

评论:也许你想要这个:

library(data.table)
dt = data.table(df)

dt[, lapply(1:3, function(i) as.character(f)[i]), by = list(a, d, b)]
#    a   d   b V1 V2 V3
# 1: 1 500 200  G  M NA
# 2: 1 500 201  G  M NA
# 3: 2 500 220  G NA NA
# 4: 2 501 220  G NA NA
# 5: 3 501 200  M NA NA
# 6: 3 501 220  M NA NA
# 7: 3 501 203  M NA NA
# 8: 3 501 204  G NA NA
# 9: 3 502 204  M NA NA
#10: 4 502 203  G NA NA
#11: 4 502 220  M NA NA
#12: 4 502 200  G  G NA