Reputation: 807
Please consider this code:
dt <- sleepstudy
fm <- lmer(Reaction ~ Days + (1|Subject), data=dt)
re <- lme4::ranef(fm)
So we have
> head(dt)
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
> head(re[[1]])
(Intercept)
308 40.787403
309 -77.856603
310 -63.114282
330 4.406841
331 10.217114
332 8.221982
What are the best ways to append the random effects to the data, to end up with
Reaction Days Subject re
1 249.5600 0 308 40.787403
2 258.7047 1 308 40.787403
3 250.8006 2 308 40.787403
4 321.4398 3 308 40.787403
5 356.8519 4 308 40.787403
6 414.6901 5 308 40.787403
etc...
Upvotes: 1
Views: 108
Reputation: 15461
You want to use merge
..
merge(dt, re, by.x= "Subject", by.y = "row.names" )
you can also use match
dt$re <- re[ match(dt$Subject, rownames(re) ) , "(Intercept)" ]
# the "(Intercept)" is whatever your column
# in re with the random effect is called
Upvotes: 3