加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 程序设计 > 正文

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

发布时间:2020-05-27 15:43:26 所属栏目:程序设计 来源:互联网
导读:是否可以在一个单独的自定义或聚合语句中包含两个函数? 下面我使用两个自动化报表和两个汇总语句:一个表示平均值,一个表示SD. 我宁愿结合这些陈述. my.Data = read.table(text = animal age sex weight 1 adult female 100 2 young male 75

是否可以在一个单独的自定义或聚合语句中包含两个函数?
下面我使用两个自动化报表和两个汇总语句:一个表示平均值,一个表示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.

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

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读