Search code examples
rlabelfactorslevelsforcats

In R methods to reduce possible error when labeling a factor with many levels


I have a variable with 75 levels, that I would like to format. However, I find it difficult to do so without formatting a level wrong.

As you know creating a factor with its levels is done like this:

df$f <- factor(df$f, levels=c('a','b','c'),
  labels=c('Treatment A','Treatment B','Treatment C'))

Is this there a way to code this differently so that the label is written next to the level. I'm looking for a code in this structure:

'a' = 'Treatment A'
'b' = 'Treatment B'
'c' = 'Treatment C'

Thanks in forward


Solution

  • You could use a named vector for your level-label-pairs and convert to a factor like so:

    foo <- c("a", "c", "b")
    
    rec <- c(
      "a" = "Treatment A",
      "b" = "Treatment B",
      "c" = "Treatment C"
    )
    
    factor(foo, levels = names(rec), labels = rec)
    #> [1] Treatment A Treatment C Treatment B
    #> Levels: Treatment A Treatment B Treatment C