【问题标题】:apply a function instead of using a loop应用函数而不是使用循环
【发布时间】:2013-12-28 05:09:55
【问题描述】:

我在文档和论坛中搜索了很长时间,但我仍然很难理解如何在 R 中使用 apply 函数而不是循环来处理更复杂的函数。 (对于 apply(data, 1, sum) 之类的函数,还可以)

例如我有以下功能

 AOV_GxT=function(Trial_group,trait,df){ 

        sub_table=df[which(df$Trial.group == Trial_group),]

        aov_GxT = anova(aov(sub_table[,trait] ~ Genotype + Treatment + Treatment/Rep.number + Genotype*Treatment, data=sub_table, na.action="na.omit"))

        pvalue = aov_GxT$"Pr(>F)"[2]
        return(c(Trial_group,trait,pvalue))  

    }

我想从数据框df 申请每个Trial_groups 和每个traits(在列中)

所以我通常会执行以下操作(效果很好):

aov_table=data.frame(matrix(ncol=4))
colnames(aov_table)=c("Trial_group", "Trait", "pvalue G*T")
for(trait in colnames(dataset)[2:ncol(dataset)]){
  for(Trial_group in unique(dataset[,'Trial.group'])){
    aov_table<-cbind (aov_table,AOV_GxT(Trial_group,trait,dataset))  
  }

dataset 是一个数据框,其中包含数据和更多包含函数中 aov 因子的列。

head(dataset)

     Trial.group     Trait1           Trait2           Trait3
          A        0.4709055        0.6123510        0.7098447
          B        0.4973123        0.6322532        0.7336145
          C        0.4955180        0.6243369        0.7336492
          D        0.4787380        0.6235426        0.7304343
          E        0.5137033        0.6418851        0.7364666
          F        0.4524246        0.5975655        0.7012825

我想限制循环的使用并学习如何使用apply族函数,所以我创建了列表并尝试使用mapply

trait_lst = list(colnames(df_vars_clean)[7:ncol(df_vars_clean)])
Tgrp_lst = list(unique(df_vars_clean[,'Trial.group']))

aov_table<-mapply(AOV_GxT(a,b,c),a=Tgrp_lst,b=trait_lst, c=dataset )

然后它给了我函数中子集的错误,我想是因为我尝试从列表中做一个子集:

“内置”类型的对象不是可子集的

我知道我的代码中可能存在一些错误,但我正在自学 R 并且有一些概念我暂时不太了解。

如何在我的函数上使用 apply 而不是多个 for 循环?

谢谢。

【问题讨论】:

  • 也许你需要在mapply调用中写list(a=Tgrp_lst,b=trait_list,c=dataset)
  • @Charles 最好在您的情况下尝试 ddply。给定您的 data.frame (df) 的 colnames 为 "Trial_group","Trait","Genotype","Treatment","Rep.number" my.func &lt;- funciton(sub_table) { anova(aov(Trait ~ Genotype + Treatment + Treatment/Rep.number + Genotype*Treatment, data=sub_table, na.action="na.omit")) }; res &lt;- ddply(df,c("Trial_group","Trait"),function(x) df$pvalue=my.func(x))

标签: r function loops subset apply


【解决方案1】:

正如 cmets 中指出的,ddply 是不错的选择,但是,lapply 也很容易解决这个问题:

do.call(rbind, lapply(split(dataset, dataset$Trial.Group), function(tgDf) {
  do.call(rbind, lapply(c("Trait1", "Trait2", "Trait3"), function(trait) {
      ## you don't need the trial group, it is already subsetted.
      AOV_gtx(trait, tgDf)
  }))
}))

使用 ddply 您将删除外部 lapply/split 代码:

ddply(dataset, "Trial.Group", function(tgDf) {
   ## the code in here would be the same, because you are iterating over
   ## the response cols.
})

所有这些函数的关键,以及一般的 R,是不要预先分配数据结构来存储结果 - 它是函数式的,因此您将构建结果然后返回它们。

【讨论】:

  • @xiaobei & jimmyb,谢谢你的帮助,我不知道 split 和 ddply 函数。效果很好!
猜你喜欢
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多