R循环anova并从列表中选择数据帧名称

时间:2015-02-10 12:27:18

标签: r variables anova

下面是一个有效的R脚本。我想anova数据帧dfa然后dfb - 但是 aov函数只读取第一个数据帧。我已搜索但未找到解决方案。更重要的是,脚本易于阅读而不是计算效率。 如何让aov循环遍历数据框? 提前谢谢。

#two dummy data frames
Obs <- c(1,2,1,4,5,6) ;Treat <- c(1,1,1,2,2,2)
dfa <- data.frame(Obs=Obs, Treat=Treat) 
Obs2 <- c(10,22,10,43,52,60)
dfb <- data.frame(Obs=Obs2, Treat=Treat)
Names <- c("dfa","dfb")

#  Loop here but cannot get it to work with calling data frame names just repeats first analysis - dfb has quite different values
for(i in 1:2) { 
print(summary(aov( Obs ~ Treat, data=as.data.frame(Names[i]))))  
print(Names[i])
}

1 个答案:

答案 0 :(得分:0)

您可以尝试

Map(function(x) summary(aov(Obs~Treat,data=x)) , mget(Names))

或者

lapply(mget(Names), function(x) summary(aov(Obs~Treat, data=x)))

如果您需要一个同时更改“调用”公式中“数据”的功能。

 f1 <- function(formula= as.formula('Obs~Treat'), data, ...){
   Call <- match.call(expand.dots=TRUE)
   Call[[1]] <- as.name('aov')
   Call$formula <- as.formula(terms(formula))
   Call$data <- as.symbol(substitute(nm, list(nm=data)))
   eval(Call)
  }

   Map(function(x,y) f1(data=y), mget(Names), Names)
   #$dfa
   #Call:
   #aov(formula = Obs ~ Treat, data = dfa)

   #Terms:
   #                 Treat Residuals
   #Sum of Squares  20.166667  2.666667
   #Deg. of Freedom         1         4

   #Residual standard error: 0.8164966
   #Estimated effects may be unbalanced

   #$dfb
   #Call:
   #aov(formula = Obs ~ Treat, data = dfb)

   #Terms:
   #                 Treat Residuals
   # Sum of Squares  2128.1667  240.6667
   #Deg. of Freedom         1         4

   #Residual standard error: 7.756718
   #Estimated effects may be unbalanced