Home > Back-end >  Mutate_ variable in a for loop
Mutate_ variable in a for loop

Time:11-10

I'm trying to mutate 8 variables (Q31_1_ through Q31_8_) with a loop with the code below which gives me the following error message : "unexpected '=' in : "Ech_final_nom_BSA <- Ech_final_nom_BSA %>% mutate_((as.name(paste("Q31_", i,"_", sep= ""))) ="

What am I doing wrong?

for (i in 1:8) {

Ech_final_nom_BSA <- Ech_final_nom_BSA %>%
  mutate_(as.name(paste("Q31_", i,"_", sep= "")) = case_when(
                    as.name(paste("Q31_", i,"_", sep= "")) == 1 ~ 4,
                    as.name(paste("Q31_", i,"_", sep= "")) == 2 ~ 3,
                    as.name(paste("Q31_", i,"_", sep= "")) == 3 ~ 2,
                    as.name(paste("Q31_", i,"_", sep= "")) == 4 ~ 1,
                    T ~ as.numeric(as.character(as.name(paste("Q31_", i,"_", sep= ""))))
                    ))
}

CodePudding user response:

mutate_ is discouraged from usage (https://dplyr.tidyverse.org/reference/se-deprecated.html). Instead, use e.g. mutate_at or across (https://dplyr.tidyverse.org/reference/across.html) and define a function similar to what you do in case_when -- except it could be more simple:

function(x) { ifelse(x %in% 1:4, 4:1[x], x) }

(or if you are certain Q31_i never lies outside of 1:4, it could be even more simple).

CodePudding user response:

You don't need a for loop. You can use mutate together with across:

Ech_final_nom_BSA %>%
  mutate(
    across(matches("^Q31_[1-8]_$"), ~case_when(
      .x %in% 1:4 ~ 4 - .x   1,
      TRUE ~ .x
    )
    ) 
  )
  • Related