2016-10-01 94 views
1

因子我需要改变从数字一列以因子基于所述数字值是高于或低于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')) 

但不行。

现在任何想法做这种类型转换?

感谢

回答

3

我们可以使用cut根据条件

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

由于只有两个层次来改变numericfactor列,另一种选择是创建一个逻辑向量并用ifelse更改值

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

如果我有2个以上的级别,比如0-7,7-15和15-20,我不能使用cut,因为输入不是数字? –

+0

@DanChaltiel目前还不清楚。请发布一个新问题。 – akrun

+0

:-) https://stackoverflow.com/questions/44285151/how-to-separate-a-vector-based-on-conditions-in-r –