是否有可能在单个tapply或聚合语句中包含两个函数?单个tapply或聚合语句中的多个函数
下面我使用两个tapply语句和两个汇总语句:一个用于平均值和一个用于标清。
我宁愿合并报表。
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
我总是可以运行两个单独的语句并合并输出。我只是希望可能有一个更方便的解决方案 。
我发现下面张贴在这里的答案: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)))
然而,无论是行或列的标签。
[,1] [,2]
[1,] 97.5 3.535534
[2,] 80.0 NA
[3,] 90.0 NA
[4,] 75.0 NA
我更喜欢base R中的解决方案。plyr
软件包的解决方案发布在上面的链接中。如果我可以将正确的行和列标题添加到上面的输出中,那将是完美的。
谢谢!这两个汇总语句有效。 tapply语句似乎不起作用,但我可以使用聚合方法。 – 2013-03-05 03:22:46
嗯,我认为它“有效”,只是不给你打印很好的东西。用(my.Data,tapply(weight,list)(age,sex),function(x){c(mean(x),sd(x))}))[1,1]'试试''在列表矩阵内部查看索引。 – 2013-03-05 03:29:20
我明白了。谢谢。如果我将整个陈述放在colnames()或rownames()中,那么我就可以得到标签。 – 2013-03-05 03:35:55