Q:

Create new column in R data frame based on grouping of other column

Using mtcars from the datasets package, I want to added an addition column that is created from mtcars$mpg, such that:
If mtcars$mpg >=15 and <19 then "Good"
If mtcars$mpg >=19 and <27 then "Average"
If mtcars$mpg >=27 then "Bad"

A:

You can use ifelse()
mtcars$mpg2 <- ifelse(mtcars$mpg >=15 & mtcars$mpg < 19,
                      "Good",
                      ifelse(mtcars$mpg >=19 & mtcars$mpg < 27,
                             "Average",
                             ifelse(mtcars$mpg > 27, "Bad", "")))

