Search code examples
rdata-cleaning

Using recode() with mutate() and across() to recode multiple variables in r


This is a question more out of curiosity since I have a working solution to my problem, but I really am curious.

I was able to recode multiple variables in a dataframe using mutate/across/case_when (with the help of answers on this site so thank you!)

But I was unable to do the same thing using recode(). Why is that?

Data setup:

library(tidyverse)

df <- data.frame(
  var1 = c(1, 2, 1, 2),
  var2 = c(1, 2, 1, 2),
  var3 = c(1, 2, 1, 2)
)

This code works:

df %>%
  mutate(across(var1:var3, ~ case_when(.x == 1 ~ "No", .x == 2 ~ "Yes")))

This code spits an error about an unexpected '='

df %>%
  mutate(across(var1:var3, ~ recode(.x, 1 = "No", 2 = "Yes")))

Why is that?


Solution

  • When recoding numbers you have to wrap them in quotes or backticks:

    library(tidyverse)
    
    df <- data.frame(
      var1 = c(1, 2, 1, 2),
      var2 = c(1, 2, 1, 2),
      var3 = c(1, 2, 1, 2)
    )
    
    df %>%
      mutate(across(var1:var3, ~ recode(.x, "1" = "No", "2" = "Yes")))
    #>   var1 var2 var3
    #> 1   No   No   No
    #> 2  Yes  Yes  Yes
    #> 3   No   No   No
    #> 4  Yes  Yes  Yes