Search code examples
rdplyrdata-wranglingrecode

Recode dataframe using R


I have a dataframe that I am trying to recode. I have done something like this before, but my code no longer works. Since the last time, I have changed versions of R studio. I am trying to recode string variables (i.e. A, B, C, etc.) into numeric variables (i.e. 5, 4, 3, etc.). Here is an example dataframe:

DF
PreQ1    PreQ2   PreQ3    PreQ4    PostQ1    PostQ2 ... PostQ4
A          A       B         C        C         D         E
B          E       A         C        B         A         B
A          A       B         C        C         D         A

Recode so "A"= 5, "B"= 4, "C"=3,"D"= 2, "E"= 1

To get this:

DF.2
PreQ1    PreQ2   PreQ3    PreQ4    PostQ1    PostQ2 ... PostQ4
 5          5       4        3       3           2        1
 4          1       5        3       4           5        4
 5          5       4        3       3           2        5

I have tried different variations on the following code without success:

DF.2<-DF %>% 
mutate(across(where(as.character), ~ recode, 'A'= 5, 'B'= 4, 'C'=3,'D'= 2, 'E'= 1))

DF.2<-DF %>% 
mutate(across(“PreQ1”: “PostQ4”), recode, 'A'= 5, 'B'= 4, 'C'=3,'D'= 2, 'E'= 1))

DF.2<-DF %>% 
 mutate(across(c(“PreQ1”: “PostQ4”), recode, 'A'= 5, 'B'= 4, 'C'=3,'D'= 2, 'E'= 1))

Any help would be appreciated!


Solution

  • You can use -

    library(dplyr)
    
    DF %>% 
      mutate(across(PreQ1:PostQ4, recode, 'A'= 5, 'B'= 4, 'C'=3,'D'= 2, 'E'= 1))
    
    #  PreQ1 PreQ2 PreQ3 PreQ4 PostQ1 PostQ2 PostQ4
    #1     5     5     4     3      3      2      1
    #2     4     1     5     3      4      5      4
    #3     5     5     4     3      3      2      5
    

    Or with a different syntax -

    DF %>% 
      mutate(across(PreQ1:PostQ4, ~recode(., 'A'= 5, 'B'= 4, 'C'=3,'D'= 2, 'E'= 1)))