Home > database >  Create new variables based on other variable and add to dataframe with loop
Create new variables based on other variable and add to dataframe with loop

Time:10-19

I have 34 variables in my set which I want to use to create new variables. Each of the variables needs a couple of transformations:

  1. Divide by IQR(variable).
  2. log(variable) And want this to happen for al 34 variables, resulting in 34 new variables, but then after these transformations. Can I do this with a loop or function?

I tried something like this, but I cannot get the newly calculated variables in my set:

exposures <- c(df$variable1, df$variable2, etc.)

for (i in exposures){
a <- i/IQR(i)
b <- log(a)
df$newvariable_IQR_log <- b 
}

Thank you for your help!

CodePudding user response:

Try this solution:

cols = names(df)
df[paste0(cols, "_IQR_log")] = lapply(df[cols], function(x) log(x/IQR(x)))

Or

library(dplyr)

df %>%
  mutate(across(everything(), ~ log(./IQR(.)), .names="{.col}_IQR_log"))
  •  Tags:  
  • r
  • Related