Search code examples
rtidyverserecodeforcats

working with factors: reordering, relabeling and recoding in R


I am having some trouble "factoring" a character variable and labeling/recoding the different levels. Is there an efficient way (i.e. less coding) to this with tidyverse or Base R such as recode or fct_collapse etc... Thank you

#This is what I have (a character variable)
x <- c("No", "Yes", "No2", "No3", "Maybe", "undecided", 
       "probably", "dont know", NA)
x
#I want a factor with three ordered levels as follows:

#where No = c("No", "No2", "No3")
#Yes = c("Yes")
#other = c("Maybe", "undecided", "probably")
#NA = c("dont know", NA)
# and the levels would be 0 = "No",  1 = "Yes" and 2 = "Maybe"
#that is:
#xfact
# [1] No    Yes   other
# Levels: No Yes other
#
# as.integer(xfact)
# [1] 0, 1, 2```

Solution

  • Something like this should do it:

    library(tidyverse)
    
    x <- c("No", "Yes", "No2", "No3", "Maybe", "undecided", 
           "probably", "dont know", NA)
    
    na_if(x, "dont know") %>% 
      fct_collapse(
        no = c("No", "No2", "No3"),
        yes = c("Yes"),
        other = c("Maybe", "undecided", "probably")
      ) %>% 
      fct_inorder()
    #> [1] no    yes   no    no    other other other <NA>  <NA> 
    #> Levels: no yes other
    

    Created on 2020-01-13 by the reprex package (v0.3.0)