[R] How to get the factor level means with interaction term?

Peng Yu pengyu.ut at gmail.com
Sun Nov 22 21:14:38 CET 2009


I thought that the last two statements in the following code should
give me the same results (what I want are the factor level means for
factor 'A'). But they don't.

I think that the last statement should give me the correct factor
level means for 'A'. Could somebody let me know what the problems are
with 'afit$coefficients[1:3]'?

set.seed(0)
a=3
b=4

A=1:a
B=1:b

n=4

X=matrix(nr=a*b*n,nc=2)
colnames(X)=LETTERS[1:2]

for(i_a in 1:a-1) {
  for(i_b in 1:b-1) {
    for(i_n in 1:n-1) {
      X[(i_a * b + i_b) * n + i_n + 1, ] = c(i_a+1, i_b+1)
    }
  }
}

Y=matrix(nr=a*b*n,nc=1)
for(i in 1:(a*b)) {
  for(i_n in 1:n-1) {
    print((i-1)*n+i_n+1,1)
    Y[(i-1)*n+i_n+1,1]= rnorm(1)
  }
}

aframe = data.frame(
    A=as.factor(X[,'A'])
    , B=as.factor(X[,'B'])
    , Y)

afit=aov(Y ~ A * B - 1, aframe)
summary(afit)
afit$coefficients[1:3]

lapply(split(aframe$Y, aframe$A),mean)




More information about the R-help mailing list