Search code examples
rloopscase-when

Looping creating new variable based on case when conditional


I'm new to R and trying to build a loop where create a new variable based on a case when conditional.

for(i in 2:10){

  variable_1 <- paste0("a_", i)

  variable_2 <- paste0("b_", i)

  variable_3 <- paste0("c_", i)

  data1 <- data1 %>%
  mutate_(variable_3 = case_when(is.na(variable_1) & !is.na(variable_2) ~ 0,
                                 TRUE ~ 1))
}

When I run this code, I can only see a new variable named variable_3 instead of creating c_2:c_10. Why is that? Would someone also explain why it doesn't work?


Solution

  • We may need to do assignment :=, evaluate (!! the expression on the lhs of :=, as well as convert the column objects as strings to symbols (sym) and evaluate (!!)

    for(i in 2:10){
    
       variable_1 <- paste0("a_", i)
       variable_2 <- paste0("b_", i)
       variable_3 <- paste0("c_", i)
       data1 <- data1 %>%
        mutate(!! variable_3 := case_when(is.na(!! rlang::sym(variable_1)) & 
         !is.na(!! rlang::sym(variable_2) )~ 0,
                                 TRUE ~ 1))
      }