Extract the level from a factor

19.3k views Asked by At

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
1

There are 1 answers

0
zx8754 On BEST ANSWER

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"