Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programmatically adding new variables to a dataframe

Tags:

dataframe

r

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?

like image 495
luciano Avatar asked Jun 17 '13 16:06

luciano


People also ask

How do you add a new variable to a data frame?

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.

How do I create a new variable in a DataFrame in R?

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.

How do you create a new variable in R based on condition?

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.


1 Answers

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 ? "[[<-"

like image 97
Beasterfield Avatar answered Oct 18 '22 09:10

Beasterfield