I am relatively new to R programming and have been using Stata mainly over the past couple of years. I have a bunch of variables of measures taken on R and L eyes but I need to create a 'treated' variable for each measure that contains the data for the treated side (given by the side variable).
I can do this simply enough using case_when in dplyr for a single variable, but how do I set this up in a loop as I have quite a few to do.
Can you use paste0 to join strings to create new variable names on the fly?
# dummy data
side <- rep(c("R","L"), each = 5, times = 5)
R_var1 <- round(rnorm(50, 20, 5),2)
L_var1 <- round(rnorm(50, 20, 5),2)
R_var2 <- round(rnorm(50, 20, 5),2)
L_var2 <- round(rnorm(50, 20, 5),2)
R_var3 <- round(rnorm(50, 20, 5),2)
L_var3 <- round(rnorm(50, 20, 5),2)
df <- data.frame(cbind(side, R_var1, L_var1, R_var2, L_var2, R_var3, L_var3))
# create 'treated' variable in the single case
df <- df %>%
mutate(., var1_treated = case_when(side == "R" ~ R_var1,
side == "L" ~ L_var1))
df
# create 'treated' variable over multiple variables in a loop
# this is where I am stuck
variables <- unique(substring(colnames(df)[2:7],3))
for(var in variables){
df <- df %>%
mutate(., paste0(variables,"_treated") = case_when(side == "R" ~ paste0("R_",variables),
side == "L" ~ paste0("L_",variables)))
}