R根据条件创建因子 [英] R create factor based on condition

查看:29
本文介绍了R根据条件创建因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据数值高于或低于 10 将一列从数字更改为因子.

I need to change a column from numeric to factor based on the numeric value being higher or lower than 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'))

但是不行.

现在有没有做这种类型转换的想法?

Any ideas now to do this type conversion?

谢谢

推荐答案

我们可以使用 cutnumeric 改为 factor 列为基础在条件

We could use cut to change the numeric to factor column based on the condition

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

这篇关于R根据条件创建因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆