【问题标题】:R create factor based on conditionR根据条件创建因子
【发布时间】:2017-02-09 17:58:30
【问题描述】:

我需要根据数值大于或小于 10 将列从数值更改为因子。

例如以下数据:

age <- c(1:20)
hight <- c(1:20)
d.frame <- data.frame(age, hight)

我尝试了以下方法:

d.frame$hight <- factor(d.frame$hight, levels( 1:9, 10:max(d.frame$hight) ), labels=c('low','high'))

d.frame$hight <- factor(d.frame$hight, levels( <10, >=10) ), labels=c('low','high'))

但不工作。

现在有什么想法来进行这种类型转换吗?

谢谢

【问题讨论】:

    标签: r type-conversion


    【解决方案1】:

    我们可以根据条件使用cutnumeric 更改为factor

    d.frame$hight <- cut(d.frame$hight, breaks = c(-Inf, 10, Inf), 
                 labels = c('low', 'high'), right = FALSE)
    

    由于只有两个级别,另一种选择是创建一个逻辑向量并使用ifelse 更改值

    d.frame$hight <- factor(ifelse(d.frame$hight>=10, "high", "low"))
    

    【讨论】:

    • 如果我有超过 2 个级别,例如 0-7、7-15 和 15-20,并且由于输入不是数字而无法使用 cut 怎么办?
    • @DanChaltiel 目前尚不清楚。请发布一个新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 2019-07-30
    • 1970-01-01
    相关资源
    最近更新 更多