Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign values to levels in factors?

Tags:

r

I want to assign values to the levels of a factor.
For example, if > 22 = mature, if <= 22 = adolescence. How can I do this? My data is:

 x <- factor(c(13, 18, 35), levels = c("adolescence", "mature"))
like image 304
Tom Avatar asked Jan 18 '26 21:01

Tom


1 Answers

Using just Base R this is a two step process.

Assuming your initial vector is numeric and not character strings (as shown above), use the cut function to define the initial factor equivalents.
Then use the "labels" option in the factor function to rename the factor levels.

factor(cut(c(13, 18, 35), breaks=c(0, 22, Inf)), labels = c("adolescence", "mature"))
#[1] adolescence adolescence mature     
#Levels: adolescence mature


Edit
As per Ben's comment, a simplified approach by adding the labels directly to the cut function:

cut(c(13, 18, 35), breaks=c(0, 22, Inf), labels = c("adolescence", "mature"))
like image 67
Dave2e Avatar answered Jan 20 '26 14:01

Dave2e



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!