Advanced Statistical Modeling with Mixed-Effects Models

Mixed-effects models are useful when dealing with data that have both fixed and random effects. We’ll use the lme4 package for this.

Step 1: Install and Load lme4

rCopy codeinstall.packages("lme4")
library(lme4)

Step 2: Create a Sample Dataset

rCopy code# Create a sample dataset with random effects
set.seed(222)
data_mixed <- data.frame(
  id = rep(1:10, each = 10),
  x = rnorm(100),
  y = rnorm(100)
)

# Introduce a random effect
data_mixed$y <- data_mixed$y + rep(rnorm(10, mean = 5, sd = 1), each = 10)

Step 3: Fit a Mixed-Effects Model

rCopy code# Fit a mixed-effects model
model_mixed <- lmer(y ~ x + (1 | id), data = data_mixed)

# Display the model summary
summary(model_mixed)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *