Search code examples
rrecode

How to recode multiple columns that do not have answers in all the factors?


I have a survey with 40 categorical variables with four answer options that I need to recode.

example of variables:

table (BD$Q12)

Never 3-5 times
104    3

table (BD$Q1)
Never 1-2 Times 3-5 Times  6+ Times
 83     16          5         2 

So far I worked with surveys of 5-8 variables, so I could solve my problems with a line of code like this:

BD$Q1 <- factor (BD$Q1, levels = c ("Never", "1-2 Times", "3-5 Times", "6 + Times"))

But I do not know how to automate it to all the columns.

I try

BD [, names] <- lapply (BD [, names], factor) 

but not all the variables have the 4 types of answers identified (they can have 1, 2, 3 or 4) so I get several types of levels. Any clue?

Thanks in advance!


Solution

  • In dplyr you could do

    library(dplyr)
    BD %>%
        mutate_all(~factor(.x, levels = c ("Never", "1-2 Times", "3-5 Times", "6 + Times")))
    

    This will recode all columns of BD.