The simple way to do this is with cut
as @Jaap mentioned. First we need to create some data the is similar to yours:
set.seed(42)
POBAD <- sample(25:40, 25, replace=TRUE)
dd <- data.frame(POBAD)
Now we add the new variable:
dd$degOB <- cut(dd$POBAD, breaks=c(0, 30, 33, max(dd$POBAD)))
levels(dd$degOB) <- 0:2
str(dd)
# 'data.frame': 25 obs. of 2 variables:
# $ POBAD: int 25 29 25 33 34 28 26 34 25 40 ...
# $ degOB: Factor w/ 3 levels "0","1","2": 1 1 1 2 3 1 1 3 1 3 ...
That is the easy way to do it. Using as.factor
just makes it more complicated, but if you want to do that, use this statement instead of the one using cut
.
dd$degOB <- as.factor(ifelse(dd$POBAD <= 30, 0, ifelse(dd$POBAD > 30 & dd$POBAD <= 33, 1, 2)))