How to Recode Multiple Columns with the Same Conditions?

I have a data set that has over 260 columns that have character values that need to be recoded as numerical factors. For example, N=0, Y=1, S=1, O=2, F=99. However, apply this to only some columns, not all, so I need to do this by column name. Here is what I have so far:

df <- data.frame(col1 = c("N", "N", "O", "N", "N", "N", "N", "N", "S", "O"),    
                  col2 = c("F", "N", "S", "O", "Y", "Y", "S", "F", "S", "O"),   
                  col3 = c("Y", "O", "Y", "N", "Y", "F", "N", "O", "S", "N"),   
                  col4 = c("S", "S", "O", "O", "Y", "S", "N", "O", "S", "N"),   
                  col5 = c("N", "S", "F", "O", "N", "F", "N", "O", "N", "N"),   
                  col6 = c("O", "N", "S", "N", "N", "N", "N", "F", "N", "O"),   
                  col7 = c("F", "F", "O", "O", "O", "N", "N", "O", "Y", "Y"),   
                  col8 = c("O", "N", "O", "S", "F", "N", "N", "Y", "S", "N"),   
                  col9 = c("N", "O", "O", "Y", "N", "S", "N", "O", "N", "Y"),   
                  col10 = c("N", "N", "S", "F", "N", "N", "F", "Y", "N", "O"))

df %>% mutate_at(.vars = c("col1", "col4", "col9"), funs(ifelse(*** == "N", 0, .)))

The 3 astericks indicate the problem. I have to specify the column name to make the recode. I run into the same problem in base R. Is there a way to do it to tell R that "these columns by name when equal to 'N' make 0".

2 Answers

You could do with across().

df <- df |> 
  mutate(across(c(col1, col4, col9), ~case_when(.x=="N" ~ 0,
                                         .x %in% c("Y","S") ~ 1,
                                         .x == "O" ~ 2,
                                         .x =="F" ~ 99)))

output

   col1 col2 col3 col4 col5 col6 col7 col8 col9 col10
1     0    F    Y    1    N    O    F    O    0     N
2     0    N    O    1    S    N    F    N    2     N
3     2    S    Y    2    F    S    O    O    2     S
4     0    O    N    2    O    N    O    S    1     F
5     0    Y    Y    1    N    N    O    F    0     N
6     0    Y    F    1    F    N    N    N    1     N
7     0    S    N    0    N    N    N    N    0     F
8     0    F    O    2    O    F    O    Y    2     Y
9     1    S    S    1    N    N    Y    S    0     N
10    2    O    N    0    N    O    Y    N    1     O

I ended up creating a function with a for-loop, looping through the names of the columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest