从因子中提取级别

时间:2015-06-23 21:11:46

标签: r

我有一个因素instrumentF

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

假设我使用[]提取此因素的一个级别。

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

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

level2$level似乎不起作用:

  

level2 $ level出错:$ operator对原子向量无效

1 个答案:

答案 0 :(得分:3)

转换为字符,请参阅此示例:

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

参见相关帖子:Convert data.frame columns from factors to characters