【发布时间】:2013-01-05 21:47:58
【问题描述】:
有人可以通过以下示例帮助我了解聚合和 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
高度赞赏所有提示、链接和批评。
【问题讨论】:
-
我认为您已经证明了不同之处。还是这里有问题?
-
好吧,虽然我看到有区别,但我不明白为什么会这样。这些函数中的什么导致了我展示的差异?
-
programming-r-pro-bro.blogspot.com/2012/12/… 的第 5 部分通过示例代码进行了精彩的解释。基本上,ddply 将允许您对每个变量使用不同的函数,而聚合则强制您对传递的所有列使用相同的函数。
标签: r