2017-03-06 48 views
-1

我怎么能循环aov()通过下面的数据集中的所有相关变量函数:一个R函数通过多次循环varialbles

set.seed(101) 
dat <- data.frame(response = rnorm(10, 5, 2), 
       gender = sample(c(0,1), 10, replace = TRUE), 
       factorA = sample (c(1:4), 10, replace = TRUE), 
       factorB = sample(c(letters[1:3]), 10, TRUE) 
> dat 
response gender factorA factorB 
4.347927  1  2  b 
6.104924  1  2  b 
3.650112  0  1  c 
5.428719  1  1  a 
5.621538  1  3  b 
7.347933  1  4  a 
6.237580  0  1  a 
4.774531  0  4  c 
6.834057  0  1  c 
4.553481  1  4  a 

我想获得和aov()输出为所有因变量(aov.factorB)等之一产生的条件:

aov.factorA <- aov(dat$response ~ dat$factorA) 
summary(aov.factorA) 

它返回:

  Df Sum Sq Mean Sq F value Pr(>F) 
dat$factorA 1 0.008 0.0077 0.005 0.945 
Residuals 8 12.287 1.5359  
+0

像这样的东西? 'res < - lapply(c(“factorA”,“factorB”),function(x)summary(aov(dat $ response〜dat [,x])))' – zx8754

+0

准确!它产生预期的产出。 – rsl

回答

1

使用lapply与您的变量名称结合起来可以做到这一点。

dependentvars <- c("factorA", "factorB") 
aov_list <- lapply(dependentvars, function(x) {summary(aov(dat$response ~ dat[, x]))}) 

现在aov_list包含aov摘要您的变量,以相同的顺序在dependentvars名称。