I am trying to simulate multi-level data for repeated measurements. My design includes just one within subjects factor, no between-subject factor. Consider the case of three treatment conditions with 10 trials in each. This is what I've written so far (using R):
##### repeated measures analysed using lme
rm(list = ls())
set.seed(374)
library(lme4)
library(reshape2)
trials_per_subject <- 30
number_of_subjects <- 30
treatment_conditions <- 3
Ntotal <- number_of_subjects*trials_per_subject
test.df <- data.frame(
subject = sort(rep(c(1:number_of_subjects),trials_per_subject)),
trial = rep(c(1:trials_per_subject),number_of_subjects) ,
x1 = rep(rep(c(1,0),c(10,20)),number_of_subjects),
x2 = rep(rep(c(0,1,0),each=10),number_of_subjects))
# random slopes
beta1 <- rnorm(number_of_subjects,40,10)
beta2 <- rnorm(number_of_subjects,40,10)
# random intercept (subject effect)
subject_effect <- rnorm(number_of_subjects,400,50)
#trial specific errors
errors <- rnorm(Ntotal,0,5)
test.df$beta1 <- beta1[test.df$subject]
test.df$beta2 <- beta2[test.df$subject]
test.df$int <- subject_effect[test.df$subject]
# factor variable for further computing in lmer()
test.df$treatment <- rep(c(1,2,3),each=10,length=Ntotal)
test.df$treatment <- as.factor(test.df$treatment)
# generate response times
test.df$y <- test.df$int + test.df$x1 * test.df$beta1 + test.df$x2 * test.df$beta2 + errors
# get correlation matrix
Df <- dcast(test.df,subject~treatment,value.var="y",fun.aggregate=mean)[,-1]
cor(Df)
# relevel so that treatment 3 becomes the reference
test.df <- within(test.df, treatment <- relevel(treatment, ref = 3))
# fit model (random intercept + slope model)
re.lm <- lmer(y ~ treatment + (1+treatment|subject), data = test.df)
summary(re.lm)
Because for repeated measurements, the correlation structure is important (sphericity), it would be necessary to be able to (indirectly) control for the assumption of sphericity/compound symmetry. To be more concise, I want manipulate whether the variances and covariances are equal (assumption met) or different (assumption violated), see dataset DF above.
rmvnorm
function here. $\endgroup$