rlme4mixed-modelslmertest

Simulating a mixed linear model and evaluating it with lmerTest in R


I am trying to understand how to use mixed linear models to analyse my data by simulating a model, but I can't reproduce the input parameters. What am I missing?

I want to start simulating a model with a random intercept for each subject. Here is the formula of what I want to simulate and reproduce: enter image description here

If beta1 (<11) is small I find gamma00 as the intercept in fixed section, but I am completedly unaable to retrieve the slope (beta1). Also, the linear effect is not significant. Where is my conceptual mistake?

library(lmerTest)
# Generating data set
# General values and variables
numObj <- 20
numSub <- 100
e      <- rnorm(numObj * numSub, mean = 0, sd = 0.1)
x      <- scale(runif(numObj * numSub, min = -100, max = 100))
y      <- c()
index  <- 1

# Coefficients
gamma00 <- 18
gamma01 <- 0.5
beta1   <- -100
w       <- runif(numSub, min = -3, max = 3)
uo      <- rnorm(numSub, mean = 0, sd = 0.1)
meanBeta0 <- mean(gamma00 + gamma01*w + uo) # I should be able to retrieve that parameter. 

for(j in 1:numSub){
  for(i in 1:numObj){
    y[index] <- gamma00 + gamma01*w[j]+ uo[j] + beta1*x[i] + e[index]
    index <- index + 1
  } 
}

dataFrame2 <- data.frame(y = y, x = x, subNo = factor(rep(1:numSub, each = numObj)), objNum = factor(rep(1:numObj, numSub))) 

model2 <- lmer(y ~  x + 
                 (1 | subNo), data = dataFrame2)
summary(model2)
anova(model2)

enter image description here


Solution

  • No conceptual mistake here, just a mixed up index value: you should be using index rather than i to index x in your data generation loop.

    Basically due to the mix-up you were using the first subject's x values for generating data for all the subjects, but using the individual x values in the model.