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?
In this example, instead of using the assign() method, we use square brackets ([]) to create a new variable or column for an existing Dataframe. The syntax goes like this: dataframe_name['column_name'] = data column_name is the name of the new column to be added in our dataframe.
To create a new variable or to transform an old variable into a new one, usually, is a simple task in R. The common function to use is newvariable <- oldvariable . Variables are always added horizontally in a data frame.
Often you may want to create a new variable in a data frame in R based on some condition. Fortunately this is easy to do using the mutate() and case_when() functions from the dplyr package.
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 ? "[[<-"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With