Skip to main content
1 of 3
mark999
  • 3.3k
  • 2
  • 25
  • 31

Repeated measures ANOVA with lme in R for two within-subject factors

I'm trying to use lme from the nlme package to replicate results from aov for repeated measures ANOVAs. I've done this for a single-factor repeated measures experiment and for a two-factor experiment with one between-subjects factor and one within-subjects factor, but I'm having trouble doing it for a two-factor experiment with two within-subjects factors.

An example is shown below. A and B are fixed-effect factors and subject is a random-effect factor.

set.seed(1)
d <- data.frame(
    Y = rnorm(48),
    subject = factor(rep(1:12, 4)),
    A = factor(rep(1:2, each=24)),
    B = factor(rep(rep(1:2, each=12), 2)))

summary(aov(Y ~ A*B + Error(subject/(A*B)), data=d))  # Standard repeated measures ANOVA

library(nlme)
# Attempts:
anova(lme(Y ~ A*B, data=d, random = ~ 1 | subject))  # not same as above
anova(lme(Y ~ A*B, data=d, random = ~ 1 | subject/(A+B)))  # gives error

I could not see an explanation of this in the Pinheiro and Bates book, but I may have overlooked it. Could anyone tell me how to do this? Thank you.

mark999
  • 3.3k
  • 2
  • 25
  • 31