Search code examples
rtidyversedata-manipulationrecode

How to gather specific columns


I am manipulating my dataset in a tidyverse fashion. However, the recode function at the end was not working. Here is an example:

olddata <- data.frame(
       x = rep(1,12),
       var_a = sample(1:10, 12, replace = TRUE),
       var_b = sample(1:10, 12, replace = TRUE),
       var_c = sample(1:10, 12, replace = TRUE))

newdata <- olddata %>%
  gather(var, type, var_a:var_c) %>%
  separate(var, into = c("var", "role"), sep = -1) %>%
  recode(role, "a"=1, "b"=2, "c"=3)

Error message says

Error in UseMethod("recode") : no applicable method for 'recode' applied to an object of class "data.frame"

What is the problem here?


Solution

  • recode is a function that returns a vector. If you're aiming for a tidyverse workflow, you can use a mutate function to get the desired result

    newdata <- olddata %>%
      gather(var, type, var_a:var_c) %>%
      separate(var, into = c("var", "role"), sep = -1) %>%
      mutate( role = recode(role, "a"=1, "b"=2, "c"=3))
    
    head(newdata)
      x  var role type
    1 1 var_    1    3
    2 1 var_    1    5
    3 1 var_    1    2
    4 1 var_    1    4
    5 1 var_    1   10
    6 1 var_    1    7