从因子中提取水平

Extract the level from a factor

我有一个因素instrumentF:

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

假设我使用 [].

提取了这个因素的一个水平
> level2 = instrumentF[1]
> level2
[1] Guitar
Levels: Cello Drums Guitar Harp

如何从因子对象 level2 中获取因子标签 Guitar

level2$level 好像不行:

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

转换为字符,看这个例子:

# 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"

查看相关内容post:Convert data.frame columns from factors to characters

或子级别:

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