Extract the level from a factor

dB' picture dB' · Jun 23, 2015 · Viewed 15.9k times · Source

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

Answer

zx8754 picture zx8754 · Jun 23, 2015

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"