Aaa <- data.frame(amount=c(1,2,1,2,1,1,2,2,1,1,1,2,2,2,1),
card=c("a","b","c","a","c","b","a","c","b","a","b","c","a","c","a"))
aggregate(x=Aaa$amount, by=list(Aaa$card), FUN=mean)
## Group.1 x
## 1 a 1.50
## 2 b 1.25
## 3 c 1.60
tapply(Aaa$amount, Aaa$card, mean)
## a b c
## 1.50 1.25 1.60
上面是一个示例代码。
似乎aggregate
和tapply
都非常方便并且执行类似的功能。
有人可以解释或举例说明他们之间的差异吗?
答案 0 :(得分:16)
aggregate
旨在使用一个函数处理多个列,并为每个类别返回一行数据框,而tapply
设计为处理单个向量,结果作为矩阵返回或阵列。仅使用双列矩阵并不能真正实现任一功能(或其显着差异)的容量。 aggregate
也有一个公式方法,tapply
没有。
> Aaa <- data.frame(amount=c(1,2,1,2,1,1,2,2,1,1,1,2,2,2,1), cat=sample(letters[21:24], 15,rep=TRUE),
+ card=c("a","b","c","a","c","b","a","c","b","a","b","c","a","c","a"))
> with( Aaa, tapply(amount, INDEX=list(cat,card), mean) )
a b c
u 1.5 1.5 NA
v 2.0 1.0 2.0
w 1.0 NA 1.5
x 1.5 NA 1.5
> aggregate(amount~cat+card, data=Aaa, FUN= mean)
cat card amount
1 u a 1.5
2 v a 2.0
3 w a 1.0
4 x a 1.5
5 u b 1.5
6 v b 1.0
7 v c 2.0
8 w c 1.5
9 x c 1.5
xtabs
函数还提供了一个R“表”,它有一个公式接口。 R表是通常具有整数值的矩阵,因为它们被设计为“列联表”,其中包含边际类别的交叉分类中的项目计数。