As far as I understand it, if an error term is part of the model model.frame.aovlist
gets the data by evaluating the call attribute of the fit, which is - attr(*, "call")= language aov(formula = weight ~ factor(Time) + Error(Chick), data = ChickWeight[ChickWeight$Diet == i, ])
. As you see, the call depends on the value of i
. Furthermore, the aovlist
object saves the name of the environment to look up the data. In this case it's R_GlobalEnv
.
Look at this:
results<-list()
counter<-1
for(i in unique(ChickWeight$Diet)){
results[[counter]] <- aov(weight~factor(Time) + Error(Chick),
data=ChickWeight[ChickWeight$Diet==i,])
counter<-counter+1
}
head(model.frame(results[[1]]), 2)
# weight factor(Time) Chick
# 461 42 0 41
# 462 51 2 41
i <- 1
head(model.frame(results[[1]]), 2)
# weight factor(Time) Chick
# 1 42 0 1
# 2 51 2 1
You can avoid the problem, if you use the split-apply-combine approach. Here is an example using by
:
res <- by(ChickWeight,ChickWeight$Diet,FUN=function(DF) {
aov(weight~factor(Time)+ Error(Chick) ,
data=DF)
})
head(model.frame(res[[1]]),2)
# weight factor(Time) Chick
#1 42 0 1
#2 51 2 1
Using this approach, the correct environment to look up the data is saved, i.e. the environment of the call of the anonymous function passed to by
.