luciano
luciano

Reputation: 13850

programmatically adding new variables to a dataframe

I've carried out this mixed effects model:

mtcarsSub <- mtcars[,c("wt", "drat", "cyl")]
library(lme4)
mtcarsME <- lmer(drat ~ (1|cyl) + wt, data=mtcarsSub)

I now want to add predictions from the model to mtcarsSub. I can add these as new variables like this:

mtcarsSub$fixed.effect <- predict(mtcarsME)
mtcarsSub$random.effect.cyl4 <- mtcarsMEFixed + ranef(mtcarsME)$cyl["4",]
mtcarsSub$random.effect.cyl6 <- mtcarsMEFixed + ranef(mtcarsME)$cyl["6",]
mtcarsSub$random.effect.cyl8 <- mtcarsMEFixed + ranef(mtcarsME)$cyl["8",]

Note that when adding the predictions from the random effects to mtcarsSub, I'm repeating myself 3 times. How can I add the predictions from the random effects programmatically, perhaps using a function and perhaps in a single line?

Upvotes: 5

Views: 906

Answers (1)

Beasterfield
Beasterfield

Reputation: 7123

Like this:

for( i in c(4,6,8) ) {
  mtcars[[ paste0("random.effect.cyl", i) ]] <- mtcarsMEFixed + ranef(mtcarsME)$cyl[as.character(i),]
}

Have alook at ? "[[<-"

Upvotes: 11

Related Questions