When working with data in R, you might want to convert numeric values into factors for easier exploratory data analysis or model building. You might also wish to control the order of factors, if the default chosen by R isn’t satisfactory. In this blog post, I’ll cover both use cases.
Changing numeric values to factors
Changing a numeric value to a factor is very easily done in R. Typically, you might have a column or multiple columns that you want to update the values for. This is done as so:
> numericValues = (sample(1:5,100, replace=TRUE))
We can use levels(numericValues) to confirm that there are none, and indeed the call returns NULL.
Now, if we wish to convert these values to factors, we can simply use factor():
> numericValues <- factor(numericValues)
 “1” “2” “3” “4” “5”
Changing the level order of factors
Now, we might wish to invert the levels of our factors, so 5 is the lowest and one is the highest. This can easily be done by using factor() in combination with levels():
> numericValues <- factor(numericValues, levels = c(5,4,3,2,1))
 “5” “4” “3” “2” “1”
Creating factors and re-ordering factor levels in R was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.