Search code examples
rintegerr-factorlevels

in R, how to set and retain custom levels in factor with different labels?


in R, how to set and retain custom levels in factor with different labels ?

That is, I want to set custom numbers in the levels of a factor, and these numerical values - integers to be retained and not converted to "1, 2, 3 etc.".

I know that one solution is to set these weights as Labels, but then I will missing the "labels" of the factor.

The "weighted" distance between factors is not retained. Is it possible in R, to achieve something like this, using a single variable ?

For example:

age_f <- factor( c(1, 10, 100), levels = c( 1, 10, 100 ), labels = c( "baby", "child", "old" ), ordered = T )
levels(age_f)
   [1] "baby"  "child" "old"  
labels(age_f)
   [1] "1" "2" "3"
 labels(levels(age_f))
    [1] "1" "2" "3"
 as.numeric(age_f)
    [1] 1 2 3

Desired output: 
 as.numeric(age_f)
        [1] 1 10 100

If this does not exists in R factors, it is easy to produce such result by a custom function?


Solution

  • You could use the labelled package for this.

    library(labelled)
    labelled(c(1, 10, 100), c(baby = 1, child = 10 , old = 100))
    
    <Labelled double>
    [1]   1  10 100
    
    Labels:
     value label
         1  baby
        10 child
       100   old
    

    If you later want to convert it into a regular factor you can use to_factor.