Matt Juchno Matt Juchno - 21 days ago 7
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

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

library(dplyr)  

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