Search code examples
rdplyrrecodeacross

Recoding multiple numeric variables in dataframe


Can someone check what mistake I am doing? All my variables are Likert scale from 1 (extremely agree) and 7 (extremely disagree). Now in regression, these give negative relation with my increasing dependent variable. Therefore I wanted to change the order of the values in data. I want to change all these variable recoded from 1-7 to 7-1. I tried the following code

Newdata <- TPBdata %>% 
  mutate_at(c("V5","V6", "V7", "V8", "V9", "V10", "V11",
              "V12", "V13", "V15", "V15", "V15_b", "V15_a",
              "V15_eco", "V18", "V19", "V20", "V21", "V24", "V26", "V25", "V22",
              funs(recode(., 7 == 1, 6 == 2, 5 == 3, 4 == 4, 3 == 5, 2 == 6, 1== 7, .default = NaN))))

I have tried with '7' = 1 also without quotes 7 = 1,

The error is

Error: .vars must be a character/numeric vector or a vars() object, not a list Run rlang::last_error() to see where the error occurred.


Solution

  • Since you are already using dplyr, I propose a dplyr solution. Also, since all the variables you inserted are in a Likert scale between 1 and 7, you can just apply to all the variables you want (indicated by the vector all_your_vars) the difference between 8 and their value - NaN will remain NaN.

    TPBdata %>% 
      mutate(across(all_your_vars, ~ 8 - .x))
    

    Example

    set.seed(42)
    TPBdata <- data.frame(
      V5 = sample(c(1:7, NaN), 5, replace = TRUE),
      V6 = sample(c(1:7, NaN), 5, replace = TRUE)
    )
    #   V5  V6
    # 1  1   4
    # 2  5   2
    # 3  1   2
    # 4  1   1
    # 5  2 NaN
    
    all_your_vars <- c("V5", "V6")
    TPBdata %>% 
      mutate(across(all_your_vars, ~ 8 - .x))
    #   V5  V6
    # 1  7   4
    # 2  3   6
    # 3  7   6
    # 4  7   7
    # 5  6 NaN