ř创建基于条件
问题描述:
因子我需要改变从数字一列以因子基于所述数字值是高于或低于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'))
但不行。
现在任何想法做这种类型转换?
感谢
答
我们可以使用cut
根据条件
d.frame$hight <- cut(d.frame$hight, breaks = c(-Inf, 10, Inf),
labels = c('low', 'high'), right = FALSE)
由于只有两个层次来改变numeric
到factor
列,另一种选择是创建一个逻辑向量并用ifelse
更改值
d.frame$hight <- factor(ifelse(d.frame$hight>=10, "high", "low"))
如果我有2个以上的级别,比如0-7,7-15和15-20,我不能使用cut,因为输入不是数字? –
@DanChaltiel目前还不清楚。请发布一个新问题。 – akrun
:-) https://*.com/questions/44285151/how-to-separate-a-vector-based-on-conditions-in-r –