R根据条件创建因子

时间:2016-10-01 06:22:19

标签: r type-conversion

我需要根据高于或低于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'))

但是不能工作。

现在有什么想法可以进行此类型转换吗?

由于

1 个答案:

答案 0 :(得分:3)

我们可以使用cut根据条件将numeric更改为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"))