There is no need for a for
loop! You can simply cbind
different response variables together.
Here is an example:
Since you don't provide a sample dataset, I generate some sample data based on the npk
dataset, where I add a second response variable yield2
which is the same as yield
with some added white noise.
set.seed(2018)
df <- npk
df$yield2 <- df$yield + rnorm(nrow(df), mean = 0, sd = 5)
Perform ANOVAs based on the two response variables yield
and yield2
res <- aov(cbind(yield, yield2) ~ block, df)
#Call:
# aov(formula = cbind(yield, yield2) ~ block, data = df)
#
#Terms:
# block Residuals
#resp 1 343.295 533.070
#resp 2 905.0327 847.2597
#Deg. of Freedom 5 18
#
#Residual standard errors: 5.441967 6.860757
#Estimated effects may be unbalanced
resp 1
and resp 2
give the sum of squares that you get if you had run aov(yield ~ block, df)
and aov(yield2 ~ block, df)
individually.
So in your case, the command would be something like
res <- aov(cbind(Y, Z) ~ Treatment)
Or if you want to run and store results from separate ANOVAs, store the response variables in a list
and use lapply
:
lapply(list(Y = "Y", Z = "Z"), function(x)
aov(as.formula(sprintf("%s ~ Treatment", x)), df))
This produces a list
of ANOVA results, where every list
element corresponds to a response variable.