Matt Juchno Matt Juchno - 2 years ago 97
R Question

R divide column into two classes

I have the attached data set ts.dilute

I want to divide the reaction column into two classes: "from 8 to 12" and "from 12 to 18". I want to call these "low" and "high" respectively. How would I do this?

Answer Source

Next time, use head(ts.dilute, 5) and copy/paste the result here instead of the screenshot.

You could use cut() to create a 2 level factor, which would make anything outside of your ranges an NA.

ts.dilute$class <- cut(ts.dilute$reaction, breaks = c(8,12,18), labels =c("low","high"), include.lowest = TRUE)

or using dplyr


ts.dilute <- ts.dilute %>%
     mutate(class = cut(reaction, breaks = c(8,12,18), labels =c("low","high"), include.lowest = TRUE)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download