Search code examples
rr-factor

Show mapping of factor levels and factor values in R


I'm wondering if there's any function to show the mapping of levels and values of a factor variable in R? For example I would expect an output like this:

Fac_level: "yes" - Value: "1",

Fac_level: "no" - Value: "2", etc.

That would be very helpful while working with unknown data sets for the first time.


Solution

  • How about this:

    x <- factor(sample(LETTERS[1:10], 20, TRUE))
    > x
    # [1] I I I H D E I H F D J G D A F F B H I F
    #Levels: A B D E F G H I J
    
    data.frame(levels = unique(x), value = as.numeric(unique(x)))
    #  levels value
    #1      I     8
    #2      H     7
    #3      D     3
    #4      E     4
    #5      F     5
    #6      J     9
    #7      G     6
    #8      A     1
    #9      B     2