R循环方差分析并从列表中选择数据框名称

R looping anova and pick data frame names from list

下面是一个有效的 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])
}

你可以试试

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

或者

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

如果您需要一个同时更改 "Call" 公式中的 "data" 的函数。

 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