Pradip Banerjee Pradip Banerjee - 1 year ago 45
R Question

Based on variable value, say Good or Better

I have a factor variable (from 0 to 23) and I want to create a category of 5 values based on this 0-23 values I have. Its like for example 0-5 says "Good", 6- 12 says " Better" etc

Answer Source

Generally speaking you are looking for function cut(). This takes a numerical vector and k+1 user-specified break points, to yield a factor with k levels.

Let's say your variable is x. Since it is a factor at the moment, we convert it to numeric before using cut():

x <- as.numeric(levels(x))[x]
cut(x, breaks = c(-0.5, 5.5, 12.5, 17.5, 23.5), labels = c("good", "better", "even better", "best")