# 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.

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
# [1] a b c d
# Levels: a b c d```
```fac2 <- factor(c(letters[3:7]))          # Create second factor vector
fac2                                     # Print second factor vector
# [1] 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
# [1] 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:

Furthermore, you might have a look at the other articles on this homepage.

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.

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Top