Robxaa798
Robxaa798

Reputation: 161

Cut numeric vector into bins

I want change the values from range to names. I have three groups and I want to change these values to names like that:

(9.94e+03,6.3e+04] -> high
(6.3e+04,1.16e+05] -> medium
(1.16e+05,1.69e+05] -> low

What i need to add in this code?

dm2 <- mutate(dm1,
              Levels.Salary = cut(dm1$Salary,3))

Upvotes: 0

Views: 60

Answers (2)

SteveM
SteveM

Reputation: 2301

To expand on GKi's answer:

breaks <- c(9.94e+03, 6.3e+04, 1.16e+05, 1.69e+05)
labels <- c("high", "medium", "low")

cuts <- cut(dm1, breaks = breaks, labels = labels)
dm2 <- cbind(dm1, cuts)

But note that your labels are in decreasing order from your breaks. Is that what you want?

Upvotes: 1

GKi
GKi

Reputation: 39737

You can use labels in cut:

cut(0:9, 3, c("low", "medium", "high"))
# [1] low    low    low    low    medium medium medium high   high   high  
#Levels: low medium high

Upvotes: 1

Related Questions