Search code examples
rfunctionrecode

Recode a set of columns in a data frame


I have a set of columns in a data frame that I want to recode in the following way (here one example with one variable):

completed_survey$little_control<-car:: recode(completed_survey$little_control, 
"1=7;2=6;3=4;4=4;5=3;6=2;7=1")

To be efficient and to not repeat the same code for all different variables, I was thinking to use a function and I was thinking something like this:

recoding <- function(x) { 
car :: recode(completed_survey$., "1=7;2=6;3=4;4=4;5=3;6=2;7=1")
} 

However, once applied to a variable in the data frame it results in the following error:

Error in `$<-.data.frame`(`*tmp*`, little_control, value = numeric(0)) : 
  replacement has 0 rows, data has 139334

I guess it's a problem in the function specification. How can I refer to any generic column-variable in the data frame so then I can apply the recoding function?


Solution

  • There are couple of issues (possibly typo) -1) unnecessary space, 2) function argument is not used inside the function. Below function have two arguments - one for data, and the next for the column name as a string

    recoding <- function(data, colName) { 
        car::recode(data[[colName]], "1=7;2=6;3=4;4=4;5=3;6=2;7=1")
      } 
    
    recoding(completed_survey, "little_control")
    

    and with a reproducible example

    recoding(mtcars, "carb")
    #[1] 4 4 7 7 6 7 4 6 6 4 4 4 4 4 4 4 4 7 6 7 7 6 6 4 6 7 6 6 4 2 8 6