多个功能在一个单一的自定义或聚合语句中

前端之家收集整理的这篇文章主要介绍了多个功能在一个单一的自定义或聚合语句中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以在一个单独的自定义或聚合语句中包含两个函数
下面我使用两个自动化报表和两个汇总语句:一个表示平均值,一个表示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,function(x) {sd(x)  }))

with(my.Data,aggregate(weight ~ age + sex,FUN = mean)
with(my.Data,FUN =   sd)

# this does not work:

with(my.Data,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,f)) )

但是,行或列都没有标记.

[,1]     [,2]
[1,] 97.5 3.535534
[2,] 80.0       NA
[3,] 90.0       NA
[4,] 75.0       NA

我更喜欢在基地R的一个soultion.从plyr包的解决方案张贴在上面的链接.如果我可以将正确的行和列标题添加到上面的输出,那将是完美的.感谢任何建议.

但这些应该有:
with(my.Data,aggregate(weight,function(x) { c(MEAN=mean(x),SD=sd(x) )}))

with(my.Data,function(x) { c(mean(x),sd(x) )} ))
# Not a nice structure but the results are in there

with(my.Data,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.

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

猜你在找的设计模式相关文章