-1

This is a picture of my column names in a value and then the anova that I have set up for it that works

I want to make a be able to switch out each column name in my anova in a loop so I don't have to rewrite the code and just change the column name.

Tried setting up a for loop and couldn't get it to work.

for (i in col_values) {
 one.way <- aov(i ~ Treatment, treatment_data)
}

Thought I'd ask here. Not particularly needing to stick with for loops, so open to any and all suggestions. Thanks for any suggestions you may have!

  • 1
    Can you provide a small example of input data using `dput()` or a built in data set, so that we can run your example? – nrennie Feb 27 '23 at 14:48

2 Answers2

1

Try wrapping it in a formula call:

for (i in col_values) {
 one.way <- aov(as.formula(paste(i, " ~ Treatment")), treatment_data)
}
nrennie
  • 1,877
  • 1
  • 4
  • 14
0
library(tidyverse)

y <- names(mtcars)[1:3] %>% 
  set_names()

map(y, ~aov(reformulate(.x, "qsec"), data = mtcars))
#> $mpg
#> Call:
#>    aov(formula = reformulate(.x, "qsec"), data = mtcars)
#> 
#> Terms:
#>                      mpg Residuals
#> Sum of Squares  17.35226  81.63589
#> Deg. of Freedom        1        30
#> 
#> Residual standard error: 1.649605
#> Estimated effects may be unbalanced
#> 
#> $cyl
#> Call:
#>    aov(formula = reformulate(.x, "qsec"), data = mtcars)
#> 
#> Terms:
#>                      cyl Residuals
#> Sum of Squares  34.60301  64.38514
#> Deg. of Freedom        1        30
#> 
#> Residual standard error: 1.464982
#> Estimated effects may be unbalanced
#> 
#> $disp
#> Call:
#>    aov(formula = reformulate(.x, "qsec"), data = mtcars)
#> 
#> Terms:
#>                     disp Residuals
#> Sum of Squares  18.61906  80.36909
#> Deg. of Freedom        1        30
#> 
#> Residual standard error: 1.636756
#> Estimated effects may be unbalanced

Created on 2023-02-27 with reprex v2.0.2

Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14