gpt4 book ai didi

r - 单个 tapply 或聚合语句中的多个函数

转载 作者:行者123 更新时间:2023-12-03 21:08:20 24 4
gpt4 key购买 nike

是否可以在单个 tapply 或聚合语句中包含两个函数?

下面我使用了两个 tapply 语句和两个聚合语句:一个用于均值,一个用于 SD。
我更愿意结合这些陈述。

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

我更喜欢基础 R 中的解决方案。来自 plyr 的解决方案包已发布在上面的链接中。如果我可以在上面的输出中添加正确的行和列标题,那就完美了。

最佳答案

但这些应该有:

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.

要遵守的原则是让您的函数返回“一件事”,它可以是向量或列表,但不能是两个函数调用的连续调用。

关于r - 单个 tapply 或聚合语句中的多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15215076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com