2016-10-01 119 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 –