Consider the sleepstudy data in the lme4 package as shown below. The contains 18 subjects with repeated measurements of Reaction (Reaction is the response) taken on different days.
library("lme4")
head(sleepstudy)
Reaction Days Subject
1 249.5600 0 308
2 258.7047 1 308
3 250.8006 2 308
4 321.4398 3 308
5 356.8519 4 308
6 414.6901 5 308
The following code fits a linear mixed model with a random intercept.
fit1 = lmer(Reaction ~ Days (1 | Subject), data = sleepstudy)
We can obtain subject-specific random intercept using "ranef(fit1)". Also, one can use "predict(fit1)" to give predictions of the response for all the time points in the original data.
However, I would like to predict the response (Reaction) in R for the 18 subjects at Day=12 and Day 14 (Day 12 and 14 are days that are not in the original data but would like to make a prediction for Reaction). That is, I should end up with a dataset that looks like this.
Days Subject Predicted_Response
12 308
12 309
...
12 371
12 372
14 308
14 309
...
14 371
14 372
CodePudding user response:
We can accomplish this with the "newdata" argument of the predict
method:
library("lme4")
fit1 = lmer(Reaction ~ Days (1 | Subject), data = sleepstudy)
newdata <- expand.grid(
Days = c(12, 14),
Subject = unique(sleepstudy$Subject)
)
newdata$Predicted_Response <- predict(fit1, newdata = newdata)
Days Subject Predicted_Response
1 12 308 417.7962
2 14 308 438.7308
3 12 309 299.1630
4 14 309 320.0976
5 12 310 313.9040
6 14 310 334.8385
7 12 330 381.4190
8 14 330 402.3536
9 12 331 387.2287
10 14 331 408.1633
11 12 332 385.2338
12 14 332 406.1683
... etc ...