Search code examples
rstringsyntaxframelevels

How this R syntax works?


For example, if we have a data frame called x in R with a column which have some levels and we want to obtain that levels as strings, this should work:

levels(x$column)[x$column]

Anyone can explain me how this R syntax works?

Thanks for your help


Solution

  • Consider a simple one column data frame:

    df <- data.frame(x=c("a", "b", "c"))
    

    The levels() function all the character levels for the input. Then, we subset that character vector using the level indices themselves:

    levels(df$x)[df$x]
    [1] "a" "b" "c"