rr-carrecode

Efficiently recoding multiple variables from character to numeric values in R


I am using R (version 3.2.3) to recode multiple variables (in the same dataframe) from character values ("High", "Medium", "Low" and "No Concerns") to numeric values (4,3,2 and 1). I know there are several ways to recode a variable and in my example below have been using the "recode" function in the car package. This works fine when recoding a single variable but when I specify multiple variables (columns 45 to 68) all the values are replaced with "N/A".

df[,c(45:68)] <- recode(df[,c(45:68)],"'High'=4;'Medium'=3;'Low'=2;'No Concerns'=1",as.numeric.result=TRUE)

I would appreciate any pointers on where I might be going wrong here. I'm new to the coding community so please let me know if I have provided enough detail in my question.


Solution

  • Try the following:

    df[,c(45:68)] <- lapply(df[,c(45:68)], function(x) 
                     recode(x,"'High'=4;
                               'Medium'=3;
                               'Low'=2;
                               'No Concerns'=1",
                                as.numeric.result=TRUE))
    

    What happens here is that you pass individual columns to recode. Looking at the helpfile of recode, you see that the function expects a numeric vector, character vector or a factor as input. In your code you provide a list, however. The above code provides individual columns to recode, which should work. Of course, without proper example data, it is difficult to tell, but give it a try.