从数字向量中获取类别

Get categories from numeric vector

我有这个数字向量:

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)怎么办?例如

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

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

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

我推荐 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
#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"