【发布时间】:2018-10-09 23:13:09
【问题描述】:
假设我有数据:
data.frame(Plot = rep(1:2,3),Index = rep(1:3, each = 2), Val = c(1:6)*10)
Plot Index Val
1 1 1 10
2 2 1 20
3 1 2 30
4 2 2 40
5 1 3 50
6 2 3 60
我想创建新列组合/聚合所有Val,这些Index 共享给定Plot 的公共Index。我想为每个Index 执行此操作。
Plot Val1 Val2 Val3
1 1 10 30 50
2 2 20 40 60
我希望任何剩余的列(例如,在这个简化示例中只是 Plot)保留在我的最终 data.frame 中。
我的尝试
我知道我可以使用aggregate() 和merge() 逐步执行此操作,但是有没有办法使用单个(或最少)调用来执行此操作?
- 任何方法都很棒,但我总是希望看到一种优雅的基本 R 方法(如果存在)...
更新:
我正在寻找一种在涉及其他列时也能正常工作的解决方案:
dat2 = data.frame(Plot = rep(1:2,each = 8),Year = rep(rep(2010:2011, each = 4),2),
Index = rep(rep(1:2,2),4), Val = rep(c(1:4)*10,4))
Plot Year Index Val
1 1 2010 1 10
2 1 2010 2 20
3 1 2010 1 30
4 1 2010 2 40
5 1 2011 1 10
6 1 2011 2 20
7 1 2011 1 30
8 1 2011 2 40
9 2 2010 1 10
10 2 2010 2 20
11 2 2010 1 30
12 2 2010 2 40
13 2 2011 1 10
14 2 2011 2 20
15 2 2011 1 30
16 2 2011 2 40
#Resulting in (if aggregating by sum, for example):
Plot Year Val1 Val2
1 1 2010 40 60
2 1 2011 40 60
3 2 2010 40 60
4 2 2011 40 60
此外,理想情况下,新列可以基于 Index 值命名。
- 因此,如果我的索引改为 A:C,我的新列将是
ValA、ValB和ValC
【问题讨论】:
-
as.data.frame.matrix(xtabs(Val~Plot+Index,dat)) -
do.call(data.frame,aggregate(Val~Plot,dat,I)) -
reshape2::dcast(dat,Plot~Index) -
tidyr::spread(dat,Index,Val) -
谢谢@Onyambu。您的
as.data.frame.matrix按预期工作(不包括Plot列,这很好,因为我可以很容易地将其添加回来)。但是,您的do.call方法无法按预期使用扩展的示例数据集(例如,使用额外的索引列)
标签: r recursion merge aggregate