0

I want to use forcats to recode factor x using a mapping like yes = "bad", yes = "2", no = "3", no = "good" but without repeating code. Something similar to yes = levels(x)[1:2] and no = levels(x)[3:4].

<!-- language-all: lang-r -->


    library(forcats)

    x <- factor(c("bad", "2", "2", "good", "3", "3", "3", "good"),
                levels = c("bad",2,3,"good"))

    fct_recode(x, yes = "bad", yes = "2", no = "3", no = "good")
    #> [1] yes yes yes no  no  no  no  no 
    #> Levels: yes no

    # I don't want to repeat yes and no
    levels(x)[1:2] # should be yes
    #> [1] "bad" "2"
    levels(x)[3:4] # should be no
    #> [1] "3"    "good"

Created on 2020-10-03 by the reprex package (v0.3.0)

sbac
  • 1,897
  • 1
  • 18
  • 31

1 Answers1

1

You can use fct_collapse :

library(forcats)
#By explicitly mentioning the levels to collapse
fct_collapse(x, yes  = c('bad', '2'), no = c('3', 'good'))
#[1] yes yes yes no  no  no  no  no 
#Levels: yes no

#By using levels
fct_collapse(x, yes  = levels(x)[1:2], no = levels(x)[3:4])
#[1] yes yes yes no  no  no  no  no 
#Levels: yes no
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213