I have a dataframe with a column of numbers.
In a separate column, I want to print whether the number is \"less than 10\", \"between 10 and 20\" or \"between 20 and 30\
do you need it to be all in one statement?
There are a few syntactical mistakes in your code, but a possible solution would be to do something like this
data$text <- "other"
data$text[data$number >=0 & data$number < 10] <- "less than 10"
data$text[data$number >=10 & data$number < 20] <- "between 10 and 20"
data$text[data$number >=20 & data$number < 30] <- "between 20 and 30"
I created a new column because if I were to replace the values in the 'number' column with text, the entire column would be coerced to character type and it might cause unexpected behaviour with the inequality operators.
You also have some overlap in your categories. Consider changing your upper bound to strictly less than (for example 20 is both >=20 and <=20, so falls into the "between 10 and 20" and "between 20 and 30" categories
If you want a one-liner, you can use the cut() function:
cut(data$number, breaks=c(0,10,20,30,Inf),
labels=c("less than 10", "between 10 and 20", "between 20 and 30", "other"))
this turns a numeric vector into factor.