轻按或汇总语句中的多个功能 [英] Multiple functions in a single tapply or aggregate statement
问题描述
是否可以在一个tapply或聚合语句中包含两个函数?
Is it possible to include two functions within a single tapply or aggregate statement?
下面我使用两个tapply语句和两个聚合语句:一个用于均值,一个用于SD。
我希望合并这些语句。
Below I use two tapply statements and two aggregate statements: one for mean and one for SD.
I would prefer to combine the statements.
my.Data = read.table(text = "
animal age sex weight
1 adult female 100
2 young male 75
3 adult male 90
4 adult female 95
5 young female 80
", sep = "", header = TRUE)
with(my.Data, tapply(weight, list(age, sex), function(x) {mean(x)}))
with(my.Data, tapply(weight, list(age, sex), function(x) {sd(x) }))
with(my.Data, aggregate(weight ~ age + sex, FUN = mean)
with(my.Data, aggregate(weight ~ age + sex, FUN = sd)
# this does not work:
with(my.Data, tapply(weight, list(age, sex), function(x) {mean(x) ; sd(x)}))
# I would also prefer that the output be formatted something similar to that
# show below. `aggregate` formats the output perfectly. I just cannot figure
# out how to implement two functions in one statement.
age sex mean sd
adult female 97.5 3.535534
adult male 90 NA
young female 80.0 NA
young male 75 NA
我总是可以运行两个单独的语句并合并输出。我只是希望可能会有
a稍微方便一些的解决方案。
I can always run two separate statements and merge the output. I was just hoping there might be a slightly more convenient solution.
我在这里找到了下面的答案:使用tapply将多个函数应用于列
I found the answer below posted here: Apply multiple functions to column using tapply
f <- function(x) c(mean(x), sd(x))
do.call( rbind, with(my.Data, tapply(weight, list(age, sex), f)) )
但是,行或列均未标记。
However, neither the rows or columns are labeled.
[,1] [,2]
[1,] 97.5 3.535534
[2,] 80.0 NA
[3,] 90.0 NA
[4,] 75.0 NA
我更喜欢基数R中的解决方案。 plyr
软件包中的解决方案发布在上面的链接中。如果我可以在上述输出中添加正确的行和列标题,那将是完美的。
I would prefer a solution in base R. A solution from the plyr
package was posted at the link above. If I can add the correct row and column headings to the above output, it would be perfect.
推荐答案
但是这些应该具有:
with(my.Data, aggregate(weight, list(age, sex), function(x) { c(MEAN=mean(x), SD=sd(x) )}))
with(my.Data, tapply(weight, list(age, sex), function(x) { c(mean(x) , sd(x) )} ))
# Not a nice structure but the results are in there
with(my.Data, aggregate(weight ~ age + sex, FUN = function(x) c( SD = sd(x), MN= mean(x) ) ) )
age sex weight.SD weight.MN
1 adult female 3.535534 97.500000
2 young female NA 80.000000
3 adult male NA 90.000000
4 young male NA 75.
要遵循的原则是让函数返回一件事,这可以是向量或列表,但不能连续调用两个函数。
The principle to be adhered to is to have your function return "one thing" which could be either a vector or a list but cannot be the successive invocation of two function calls.
这篇关于轻按或汇总语句中的多个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!