tapply和ave之间的功能有什么区别? [英] What is the difference between the functions tapply and ave?

查看:117
本文介绍了tapply和ave之间的功能有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能全神贯注于 ave 函数。我阅读了帮助并搜索了网络,但仍然无法理解它的作用。我了解它在观察的子集上应用了某些功能,但不是像 tapply

I can't wrap my mind around the ave function. I read the help and searched the net but I still cannot understand what it does. I understand it applies some function on a subset of observation but not in the same way as for example tapply

有人请举个小例子来启发我吗?

Could someone please enlighten me perhaps with a small example?

谢谢,请原谅我一个不寻常的请求。

Thanks, and excuse me for perhaps an unusual request.

推荐答案

tapply 返回每个因子水平的单个结果。 ave 还会在每个因子水平上产生单个结果,但会将其复制到原始数据中的每个位置。

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 在包含摘要数据的数据框中生成新列非常方便。

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

一个简短的示例:

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 产生150个结果,该结果与原始数据框一致:

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

感谢Josh和thelatemail。

Thanks to Josh and thelatemail.

这篇关于tapply和ave之间的功能有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆