Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ifelse to transform column in R

Tags:

r

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" based on the number.

I have produced this code so far which doesn't work so far, can anyone suggest how I can amend this so that it does?

#create some data
data<-data.frame(number=(1:40))

#ifelse statement
data$words<-
ifelse(data[,"number"]>=0&&<=9,"less than 10",
ifelse(data[,"number"]>=10&&<=20,"between 10 and 20",
ifelse(data[,"number"]>=20&&<=30,"between 20 and 30", "other")))  
like image 792
Basil Avatar asked Feb 07 '26 23:02

Basil


1 Answers

You could use cut from base R, but be aware it makes the words variable a factor. You just need to set the appropriate intervals (which is why I used 30.5 etc for readibility). BTW, in your example you coded 20 should be recoded both to "between 10 and 20" and to "between 20 and 30", which won't work.

data$words <- cut(data$number, c(0,9.5,20.5,30.5,40), c("less than 10", "between 10 and 20", "between 20 and 30", "other"))
data
like image 71
Lennyy Avatar answered Feb 09 '26 11:02

Lennyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!