问题
I have this numeric vector:
vec <- 1:7
How can I transform it into 3 categories using these logical rules:
if(vec >= 1 && vec < 4) then "category1"
else if(vec >=4 && vec < 6) then "category2"
else if(vec >= 6 && vec < 8) then "category3"
The expected result would be:
result <- c("category1","category1","category1",
"category2","category2",
"category3","category3")
UPDATE:
What if category names are not sequential (i.e. 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"
回答1:
I'd recommend cut
and its labels
variable
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
回答2:
#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"
来源:https://stackoverflow.com/questions/29055574/get-categories-from-numeric-vector