从数字向量中获取类别

时间:2015-03-14 23:42:14

标签: r categories numeric

我有这个数字向量:

vec <- 1:7

如何使用这些逻辑规则将其转换为3个类别:

if(vec >= 1 && vec < 4) then "category1"

else if(vec >=4 && vec < 6) then "category2"

else if(vec >= 6 && vec < 8) then "category3"

预期结果将是:

result <- c("category1","category1","category1",
            "category2","category2",
            "category3","category3")

更新:

如果类别名称不是连续的(即cat1,cat2,cat3)怎么办? e.g。

if(vec >= 1 && vec < 4) then "night"

else if(vec >=4 && vec < 6) then "early morning"

else if(vec >= 6 && vec < 8) then "morning"

2 个答案:

答案 0 :(得分:5)

我建议cut及其labels变量

cut(vec, c(1, 3, 5, 8), include.lowest = TRUE, labels = paste0("category", 1:3))
# [1] category1 category1 category1 category2 category2 category3 category3
# Levels: category1 category2 category3

答案 1 :(得分:3)

#a. `ifelse` approach

result<-ifelse(vec >= 1 & vec < 4,"category1",ifelse(vec >=4 & vec < 6,"category2","category3"))
[1] "category1" "category1" "category1" "category2" "category2" "category3" "category3"

#b. `Recode` from car package

library(car)
result<- Recode(vec,"1:3='category1';4:6='category2';else='category3'")
[1] "category1" "category1" "category1" "category2" "category2" "category2" "category3"