2
$\begingroup$

Suppose we have $m$ schools chosen randomly from among thousands in a large country. Suppose also that $n$ students of the same age are chosen at each school. Let $Y_{ij}$ be the score of the $j$th student at the $i$th school.

One model we can come up with is:

$$ Y_{ij} = \mu + U_i + W_{ij} $$

where the $\mu$ variable is the average score for the entire population. From this model, $U_i$ is a random effect with $W_{ij}$ being the error term. Suppose that I want $U_i$ to be normally distributed. That is, each school has a different normal distribution parameter: $U_i$.

I am wondering how a scenario like this can be simulated in R, for say $m = 5$ schools, $n = 100$ students?

$\endgroup$

1 Answer 1

3
$\begingroup$

Simulate random effect model.

m <- 5 #number of schools
mu <- 12.56 # global score average
sdU <- 5.67 # standard deviation for the random effect
sdW <- 3.25 # standard deviation for the noise

# values for the random effect
U <- rnorm(m, mean=0, sd = sdU)

# Number of observations in each school
n <- 100

N <- m*n

data <- data.frame(school = rep(1:m, each=n))
data$U <- U[data$school] # random factor value for each school
data$val <- rnorm(m*n, mu + data$U, sdW)

library(lme4)
library(lmerTest)

# Estimate parameters set earlier
m1 <- lmer(val ~ 1 + (1|school), data = data)
summary(m1)

# If you look at the summary and the Random Effects section, the estimates for 
# schools (sdU) and for the noise (sdW) should be close to those defined above.
sU <- sdU^2 # Variance (only for the reference)
sW <- sdW^2 # Variance (only for the reference)
```
$\endgroup$
3
  • 2
    $\begingroup$ Are the lines sU <- sda^2; sW <- sdf^2 supposed to be included? sda and sdf aren't defined, and sU and sW are never used. $\endgroup$
    – zephryl
    Jun 2, 2023 at 16:59
  • $\begingroup$ I've downvoted this answer because this code doesn't work (for the reasons already stated) and is effectively misleading. The answerer may consider editing the answer to include actionable code. $\endgroup$ Jun 22, 2023 at 15:01
  • $\begingroup$ Thanks for pointing that out! I have corrected the code. It should be working now. $\endgroup$ Jun 23, 2023 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.