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"))
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With