ddply和聚合之间的区别

时间:2013-01-05 21:47:59

标签: r

有人可以通过以下示例帮助我区分聚合和ddply:

数据框:

mydat <- data.frame(first = rpois(10,10), second = rpois(10,10), 
                    third = rpois(10,10), group = c(rep("a",5),rep("b",5)))

使用聚合将函数应用于按因子分割的数据框的一部分:

aggregate(mydat[,1:3], by=list(mydat$group), mean)
  Group.1 first second third
1       a   8.8    8.8  10.2
2       b   6.8    9.4  13.4

尝试将聚合用于其他函数(返回错误消息):

aggregate(mydat[,1:3], by=list(mydat$group), function(u) cor(u$first,u$second))
Error in u$second : $ operator is invalid for atomic vectors

现在,尝试使用ddply(plyr包):

ddply(mydat, .(group), function(u) cor(u$first,u$second))
  group         V1
1     a -0.5083042
2     b -0.6329968

所有提示,链接,批评都非常感谢。

3 个答案:

答案 0 :(得分:14)

aggregate独立调用每列的FUN,这就是您获得独立方式的原因。 ddply将把所有列传递给函数。快速演示aggregate中传递的内容可能是有序的:

用于演示的一些示例数据:

d <- data.frame(a=1:4, b=5:8, c=c(1,1,2,2))

> d
  a b c
1 1 5 1
2 2 6 1
3 3 7 2
4 4 8 2

通过使用函数print并忽略命令aggregateddply的结果,我们可以看到在每次迭代中传递给函数的内容。

aggregate

tmp <- aggregate(d[1:2], by=list(d$c), print)
[1] 1 2
[1] 3 4
[1] 5 6
[1] 7 8

请注意,会发送各列以进行打印。

ddply

tmp <- ddply(d, .(c), print)
  a b c
1 1 5 1
2 2 6 1
  a b c
3 3 7 2
4 4 8 2

请注意,数据框正在发送打印。

答案 1 :(得分:8)

你已经被告知为什么aggregate是一个错误的{base}函数用于需要两个向量作为参数的函数,但是你还没有被告知哪个非ddply方法会成功

by( ... grp, FUN)方法:

> cbind (by( mydat, mydat["group"], function(d) cor(d$first, d$second)) )
        [,1]
a  0.6529822
b -0.1964186

sapply(split( ..., grp), fn)方法

> sapply(  split( mydat, mydat["group"]), function(d) cor(d$first, d$second)) 
         a          b 
 0.6529822 -0.1964186 

答案 2 :(得分:6)

@MatthewLundberg的答案非常好,我的答案不是答案,但这只是我想看看一些R函数调用背后发生了什么的一般提示。我使用调试命令browser

aggregate(mydat[,1:3], by=list(mydat$group), 
+           function(x){
+             browser()
+             mean(x)
+           })
Called from: FUN(X[[1L]], ...)
Browse[1]> x
[1] 16 10 16 13 25

然后是ddply

ddply(mydat, .(group), function(u) {
+   browser()
+   cor(u$first,u$second)
+   })
Called from: .fun(piece, ...)
Browse[1]> u
  first second third group
1    16      8     9     a
2    10      6     6     a
3    16      6    10     a
4    13      8    10     a
5    25     10     4     a

编辑自己调试错误

在这里,我使用该技术来了解您收到错误的原因

aggregate(mydat[,1:3], by=list(mydat$group), function(u) {
+   browser()
+   cor(u$first,u$second)
+   })
Called from: FUN(X[[1L]], ...)
Browse[1]> u
[1] 16 10 16 13 25    

如你所见,你是一个原子矢量(没有列名) 所以如果你试试

Browse[1]> u$first

您收到错误消息:

Error in u$first : $ operator is invalid for atomic vectors
相关问题