Search code examples
rcategorical-data

Extract the level from a factor


I have a factor instrumentF:

> instrumentF
[1] Guitar Drums  Cello  Harp  
Levels: Cello Drums Guitar Harp

Let's say I extract one level of this factor using [].

> level2 = instrumentF[1]
> level2
[1] Guitar
Levels: Cello Drums Guitar Harp

How I can get the factor label Guitar from the factor object level2?

level2$level doesn't seem to work:

> Error in level2$level : $ operator is invalid for atomic vectors

Solution

  • Convert to character, see this example:

    # factor variable example
    instrumentF <- as.factor(c("Guitar", "Drums", "Cello", "Harp"))
    
    instrumentF
    # [1] Guitar Drums  Cello  Harp  
    # Levels: Cello Drums Guitar Harp
    
    as.character(instrumentF)[ 1 ]
    # [1] "Guitar"
    

    See relevant post: Convert data.frame columns from factors to characters

    Or subset the level:

    # as levels are sorted alphabetically, we need to subset the 3rd one
    levels(instrumentF)[ 3 ]
    # [1] "Guitar"