Combine Factors without Changing Levels to Integer in R (Example)
In this article you’ll learn how to keep factor levels when merging two factors in R.
Table of contents:
So without further additions, here’s how to do it:
Creation of Example Data
We’ll use the following data as basement for this R programming tutorial:
fac1 <- factor(c(letters[1:4])) # Create first factor vector fac1 # Print first factor vector #  a b c d # Levels: a b c d
fac2 <- factor(c(letters[3:7])) # Create second factor vector fac2 # Print second factor vector #  c d e f g # Levels: c d e f g
The previous outputs of the RStudio console shows that our example factors are two vector objects with four and five different factor levels.
Some of those factor levels are contained in both factors, and some factor levels are contained only in one of the factors.
Example: Concatenate Two Factors without Converting to Integer Level
The following R code shows how to merge multiple factors with different factor levels without changing the factor levels to integer numbers.
For this task, we can apply the list and unlist functions as shown below:
fac_combi <- unlist(list(fac1, fac2)) # Combine factors fac_combi # Print combined factors #  a b c d c d e f g # Levels: a b c d e f g
Have a look at the previous output: We have created a new factor variable containing all values and factor levels of the two input vectors.
Video, Further Resources & Summary
Some time ago, I have published a video on my YouTube channel, which demonstrates how to join factor levels based on the R syntax of this tutorial. You can find the video tutorial below:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you might have a look at the other articles on this homepage.
- Convert Discrete Factor to Continuous Variable
- Group Factor Levels in R
- Get All Factor Levels of Vector & Data Frame Column
- Replace Values in Factor Vector or Column
- Count Observations by Factor Level in R
- Reorder Levels of Factor without Changing Order of Values
- Introduction to R
In summary: In this R programming tutorial you have learned how to retain factor levels when combining two factors. Note that we could apply the same syntax as shown in this tutorial to concatenate and append data frame columns with the factor class. If you have any additional comments and/or questions, please tell me about it in the comments section. Furthermore, don’t forget to subscribe to my email newsletter in order to get updates on new tutorials.
Statistics Globe Newsletter