我需要根据数值高于或低于 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'))
and
d.frame$hight <- factor(d.frame$hight, levels( <10, >=10) ), labels=c('low','high'))
但不要工作。
现在有什么想法可以进行这种类型转换吗?
Thanks
我们可以使用cut
改变numeric
to 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"))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)