gpt4 book ai didi

r - 从因子中提取水平

转载 作者:行者123 更新时间:2023-12-03 15:52:01 26 4
gpt4 key购买 nike

我有一个因素 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似乎不起作用:
> 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"

见相关帖子: 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"

关于r - 从因子中提取水平,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31013611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com