I have a data frame that contains random values between 0-60 (inclusive 0 & 60). These values denote months. I want to bin the data into three categories (x<=6, 6< x <=12, x>12) and generate a new single columns which will be a factor containing 3 values (0,1,2) denoting the respective bins.

I am able to generate 3 columns one-hot encoded style but I am unable to think of a way to generate single column having 3 factors.


1 Answer 1


Use cut:

> df = data.frame(v=sample(1:60,1000,TRUE))
> df$cat = cut(df$v,c(-Inf,6,12,Inf))
> table(df$cat)

 (-Inf,6]    (6,12] (12, Inf] 
       97        92       811 

Also, simple R questions are better asked on StackOverflow.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.