在R中使用`apply`的变体 [英] Using variations of `apply` in R
本文介绍了在R中使用`apply`的变体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常在研究中,我们必须做一个汇总表.我想在R中使用tapply
创建一个表.唯一的问题是我有40个变量,并且我希望基本上对所有40个变量执行相同的操作.这是数据示例
Often times in research we have to do a summary table. I would like to create a table using tapply
in R. The only problem is I have 40 variables and I would like to basically perform the same operation for all 40 variables. Here is an example of the data
Age Wt Ht Type
79 134 66 C
67 199 64 C
39 135 78 T
92 149 61 C
33 138 75 T
68 139 71 C
95 198 62 T
65 132 65 T
56 138 81 C
71 193 78 T
基本上,我想让它产生给定 Type 的所有变量的均值.看起来应该是
Essentially I would like to get it to produce the means of all the variables given the Type. It should look as
C T
Age 72.4 60.6
Wt 151.8 159.2
Ht 68.6 71.6
我尝试使用
sapply(df, tapply(df, df$Type, mean))
但出现错误.
任何指导将不胜感激.
Any guidance would be appreciated.
推荐答案
尝试:
> sapply(df[1:3], tapply, df$Type, mean)
Age Wt Ht
C 72.4 151.8 68.6
T 60.6 159.2 71.6
或者您可以使用colMeans
:
> sapply(split(df[1:3], df$Type), colMeans)
C T
Age 72.4 60.6
Wt 151.8 159.2
Ht 68.6 71.6
这篇关于在R中使用`apply`的变体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文