Reputation: 97
I have the following sample data:
structure(list(Class = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L,
4L, 5L, 5L), .Label = c("A", "B", "C ", "D ", "E"), class = "factor"),
a = c(0.10881116, 0.526242737, 0.982902999, 0.320738663,
0.652972541, 0.039061302, 0.866235756, 0.319948863, 0.49249116,
0.387460274), b = c(0.962253789, 0.504883561, 0.958827249,
0.112715995, 0.481341694, 0.022454068, 0.365585675, 0.243682534,
0.540064663, 0.79933528), c = c(0.68491864, 0.170941001,
0.067239671, 0.350063079, 0.303616697, 0.811791432, 0.986189818,
0.261161444, 0.366817736, 0.393204464), d = c(0.171410187,
0.795272464, 0.127037962, 0.729957086, 0.783967392, 0.836820247,
0.39774571, 0.727385402, 0.191486044, 0.316815623), e = c(0.018072241,
0.360542881, 0.435783461, 0.557028064, 0.645997614, 0.631136435,
0.316623636, 0.871827327, 0.615828269, 0.956653665), f = c(0.152489388,
0.500431046, 0.249617685, 0.855327742, 0.578962117, 0.510960229,
0.910920471, 0.8616062, 0.301616817, 0.691359783), g = c(0.016796537,
0.597620997, 0.169782711, 0.190080222, 0.781218649, 0.323382447,
0.968615432, 0.287030348, 0.754648917, 0.720887331)), class = "data.frame", row.names = c(NA,
-10L))
I'm looking to run several one-way ANOVAs. I want to run ANOVAs between "Class" (A, B, C, D, etc.) for each column independently (i.e. one anova for "a", another for "b", another for "c", etc. for a total of 7 ANOVAs). For each, I want to run a Scheffe post-hoc test.
So, for instance, for one ANOVA, the code would be
res.aov <- aov(a ~ Class, data = df)
library(DescTools)
ScheffeTest(res.aov)
Is there a way to run all ANOVAs at once?
Upvotes: 1
Views: 249
Reputation: 886938
We can do this in a loop
library(DescTools)
out <- lapply(names(df)[-1], function(nm)
ScheffeTest(aov(reformulate('Class', nm), data = df)))
names(out) <- names(df)[-1]
In the dput
output, find some leading/lagging spaces for 'Class'
df$Class <- trimws(df$Class)
Just in case, the formula can also be constructed with paste
out <- lapply(names(df)[-1], function(nm)
ScheffeTest(aov(as.formula(paste(nm, "~", "Class")), data = df)))
names(out) <- names(df)[-1]
Or with sprintf
out <- lapply(names(df)[-1], function(nm)
ScheffeTest(aov(as.formula(sprintf("%s ~ Class", nm)), data = df)))
names(out) <- names(df)[-1]
Or if we decide to do this in tidyverse
library(purrr)
library(dplyr)
map(names(df)[-1], ~ aov(reformulate('Class', .x), data = df) %>%
ScheffeTest)
Upvotes: 2