问题
everybody. I hope that you would help me to solve my query. For a vector representing the price ($) of apples say,
apple <- c(23, 26, 54, 34, 34, 34, 98, 23, 4, 34, 098, 45, 93, 20, 39, 83, 78, 34, 09, 8, 56, 98, 99, 62, 29)
I can assign a factor vector that represents whether it is "cheap" if apples cost less than $50 and "expensive" if apple cost more than or equal to $50. For instance, the factor variable could easily be assigned as:
price <- factor(apple>50, labels = c("cheap", "expensive"))
However, I am clueless of assigning a factor variable with three levels of price say cheap, moderate, and expensive, say when apples are said to be of a moderate price if they cost between $30 and $40. Thank you
回答1:
We can use cut
:
cut(apple, breaks = c(0, 30, 40, Inf), labels = c("Cheap", "Moderate", "Expensive"))
#> [1] Cheap Cheap Expensive Moderate Moderate Moderate Expensive Cheap
#> [9] Cheap Moderate Expensive Expensive Expensive Cheap Moderate Expensive
#> [17] Expensive Moderate Cheap Cheap Expensive Expensive Expensive Expensive
#> [25] Cheap
#> Levels: Cheap Moderate Expensive
回答2:
We can use findInterval
in base R
c('Cheap', 'Moderate', 'Expensive')[findInterval(apple, c(0, 30, 40))]
#[1] "Cheap" "Cheap" "Expensive" "Moderate" "Moderate" "Moderate" "Expensive" "Cheap" "Cheap" "Moderate" "Expensive"
#[12] "Expensive" "Expensive" "Cheap" "Moderate" "Expensive" "Expensive" "Moderate" "Cheap" "Cheap" "Expensive" "Expensive"
#[23] "Expensive" "Expensive" "Cheap"
来源:https://stackoverflow.com/questions/62249006/assign-a-factor-vector-with-more-than-2-levels-labels-for-a-given-numeric-numeri