Home > OS >  How can I recode this variable in R (reverse coding)
How can I recode this variable in R (reverse coding)

Time:02-15

I currently have this variable 'q1', which is based on a likert scale. Currently a 1 corresponds to 'Always', 2 corresponds to 'Most of the time', 3 corresponds to 'Sometimes', 4 corresponds to 'Rarely', and 5 corresponds to 'Never'.

I want to reverse code this variable so that 1 corresponds to 'Never', 2 corresponds to 'Rarely', 3 corresponds to 'Sometimes', 4 corresponds to 'Most of the time', and 5 corresponds to 'Always'. This will be more consistent with the other variables and their coding scheme.

Thanks!

> dput(df$q1)
c(3L, 4L, 3L, 3L, 4L, 3L, 3L, 5L, 3L, 3L, 3L, 3L, 4L, 3L, 5L, 
2L, 3L, 2L, 3L, 4L, 1L, 4L, 4L, 4L, 1L, 1L, 4L, 1L, 2L, 3L, 1L, 

CodePudding user response:

Try the plyr package's mapvalues() function

library(plyr)

# Your data
q1<-c(3L, 4L, 3L, 3L, 4L, 3L, 3L, 5L, 3L, 3L, 3L, 3L, 4L, 3L, 5L, 
      2L, 3L, 2L, 3L, 4L, 1L, 4L, 4L, 4L, 1L, 1L, 4L, 1L, 2L, 3L, 1L)
  
  mapvalues(q1,
            from=c(1:5),
            to=c('Never',
                 'Rarely',
                 'Sometimes',
                 'Most of the time',
                 'Always'))
  •  Tags:  
  • r
  • Related