Replace multiple values over multiple columns of a data frame in R

Viewed 26

I am trying to replace certain numbers with others over multiple columns of a data set.

1=1
2=1
3=2
4=3
5=3

So if I have:


id      age        A1       weight     Var1       A2    
  
3       5          2         50         1         4
7       23         1         67         5         3
9       78         4         90         3         2
12      14         1         17         2         3

I want to replace those numbers in columns A1, Var1, and A2


id      age        A1       weight     Var1       A2    
  
3       5          1         50         1         3
7       23         1         67         3         2
9       78         3         90         2         1
12      14         1         17         1         2



I think I can do something with mutate_across but I'm not sure

1 Answers
df1 %>%
   mutate(across(c(A1, Var1, A2), recode, "1" = 1,
                 "2" = 1, `3` = 2, `4` = 3, `5` = 3))

  id age A1 weight Var1 A2
1  3   5  1     50    1  3
2  7  23  1     67    3  2
3  9  78  3     90    2  1
4 12  14  1     17    1  2
Related