What is the difference between the functions tapply and ave?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 05:23:54

tapply returns a single result for each factor level. ave also produces a single result per factor level, but it copies this value to each position in the original data.

ave is handy for producing a new column in a data frame with summary data.

A short example:

tapply(iris$Sepal.Length, iris$Species, FUN=mean)
    setosa versicolor  virginica 
     5.006      5.936      6.588 

One value, the mean for each factor level.

ave on iris produces 150 results, which line up with the original data frame:

 ave(iris$Sepal.Length, iris$Species, FUN=mean)
  [1] 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006
 [17] 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006
 [33] 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006 5.006
 [49] 5.006 5.006 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936
 [65] 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936
 [81] 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936 5.936
 [97] 5.936 5.936 5.936 5.936 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588
[113] 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588
[129] 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588 6.588
[145] 6.588 6.588 6.588 6.588 6.588 6.588

As noted in the comments, here the single value is being recycled to fill each location in the original data.

If the function returns multiple values, these are recycled if necessary to fill in the locations. For example:

d <- data.frame(a=rep(1:2, each=5), b=1:10)
ave(d$b, d$a, FUN=rev)
 [1]  5  4  3  2  1 10  9  8  7  6

Thanks to Josh and thelatemail.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!