十一、apply家族(4)

tapply()函数

tapply()函数主要是用于对一个因子或因子列表,执行指定的函数调用,最后获得汇总信息。
tapply()函数的使用格式如下所示。
tapply(x, INDEX, FUN, ...)
x:要处理的对象。
INDEX:因子或分类的字符串向量或因子列表。
FUN:要使用的函数。
... :FUN函数所需要的额外参数。

R 复制代码
height = c(172, 175, 168, 173, 176)
gender = c('M','F', 'F', 'M', 'F')    #"F":女(female);"M":男(male)

tapply(height, gender, mean)          #求女性、男性身高的平均值
    F     M 
173.0 172.5

tapply(height, gender, max)          ##求女性、男性身高的最大值
  F   M 
176 173 

下面以R语言内置数据集鸢尾花iris为例。
鸢尾花的3种类型( 山鸢尾(setosa)、变色鸢尾(versicolor)和维吉尼亚鸢尾(virginica) )。

R 复制代码
head(iris)        #记录了花萼的长度、宽度;花瓣的长度、宽度;种类
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

查看iris数据集的元素类型。

R 复制代码
sapply(iris, class)
Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
   "numeric"    "numeric"    "numeric"    "numeric"     "factor"    #数值;因子

计算不同种类鸢尾花的花瓣长度、宽度平均值。

R 复制代码
tapply(iris$Petal.Length, iris$Species, mean)    #不同种类花瓣长度的平均值
setosa versicolor  virginica 
 1.462      4.260      5.552


tapply(iris$Petal.Width, iris$Species, mean)     #不同种类花瓣宽度的平均值
setosa versicolor  virginica 
 0.246      1.326      2.026 
相关推荐
Chef_Chen3 小时前
从0开始学习R语言--Day40--Kruskal-Wallis检验
开发语言·学习·r语言
quant_19867 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
小白学大数据2 天前
R语言爬虫实战:如何爬取分页链接并批量保存
开发语言·爬虫·信息可视化·r语言
开开心心_Every3 天前
便捷的Office批量转PDF工具
开发语言·人工智能·r语言·pdf·c#·音视频·symfony
Chef_Chen4 天前
从0开始学习R语言--Day39--Spearman 秩相关
开发语言·学习·r语言
q567315236 天前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone
shootero@126.com7 天前
R语言开发记录,二(创建R包)
r语言
shootero@126.com7 天前
R语言开发记录,一
开发语言·r语言
旷世奇才李先生7 天前
R 语言安装使用教程
开发语言·r语言
十三画者18 天前
【科研绘图系列】R语言绘制circos图形(circos plot)
数据挖掘·数据分析·r语言·数据可视化