5

I have a numerical variable (QS) which ranges from 1-10. I would like to create a categorical variable where

Bad: QS < 5, and Good: QS > 5

So I would now have 2 categorical variables...Good and Bad

What is the best way to do this in R?

1 Answers1

10

I would recommend cut or factor+levels here. A small example:

set.seed(1)
QS <- sample(10, 15, replace = TRUE)
QS
#  [1]  3  4  6 10  3  9 10  7  7  1  3  2  7  4  8
cut(QS, c(0, 5, 10), labels=c("Bad", "Good"))
#  [1] Bad  Bad  Good Good Bad  Good Good Good Good Bad  Bad  Bad  Good Bad  Good
# Levels: Bad Good
X <- factor(QS)
levels(X) <- list(Bad = 1:5, Good = 6:10)
X
#  [1] Bad  Bad  Good Good Bad  Good Good Good Good Bad  Bad  Bad  Good Bad  Good
# Levels: Bad Good
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485