我使用的一种设计模式是在数据帧上执行“分组,分组,应用,组合(SAC)”,然后将聚合数据加入原始数据。这是有用的,例如,当计算每个县的偏离状态平均数在一个数据帧与许多州和县。很少是我的总体计算只是一个简单的意思,但它是一个很好的例子。我经常以下列方式解决这个问题:
require(plyr) set.seed(1) ## set up some data group1 <- rep(1:3,4) group2 <- sample(c("A","B","C"),12,rep=TRUE) values <- rnorm(12) df <- data.frame(group1,group2,values) ## got some data,so let's aggregate group1Mean <- ddply( df,"group1",function(x) data.frame( meanValue = mean(x$values) ) ) df <- merge( df,group1Mean ) df
它产生好的汇总数据,如下所示:
> df group1 group2 values meanValue 1 1 A 0.48743 -0.121033 2 1 A -0.04493 -0.121033 3 1 C -0.62124 -0.121033 4 1 C -0.30539 -0.121033 5 2 A 1.51178 0.004804 6 2 B 0.73832 0.004804 7 2 A -0.01619 0.004804 8 2 B -2.21470 0.004804 9 3 B 1.12493 0.758598 10 3 C 0.38984 0.758598 11 3 B 0.57578 0.758598 12 3 A 0.94384 0.758598
一行代码的诀窍在于:
原文链接:https://www.f2er.com/javaschema/282120.htmlnew <- ddply( df,transform,numcolwise(mean)) new group1 group2 values meanValue 1 1 A 0.48742905 -0.121033381 2 1 A -0.04493361 -0.121033381 3 1 C -0.62124058 -0.121033381 4 1 C -0.30538839 -0.121033381 5 2 A 1.51178117 0.004803931 6 2 B 0.73832471 0.004803931 7 2 A -0.01619026 0.004803931 8 2 B -2.21469989 0.004803931 9 3 B 1.12493092 0.758597929 10 3 C 0.38984324 0.758597929 11 3 B 0.57578135 0.758597929 12 3 A 0.94383621 0.758597929 identical(df,new) [1] TRUE