Convert NA into Factor Level in R (Example) | addNA Function for Missing Data
This article explains how to turn NA values into a new factor level using the addNA function in the R programming language.
Table of contents:
Let’s start right away!
Example Data
The following data will be used as basement for this R tutorial:
my_fac <- factor(c("a", "b", NA, "a", "c", NA)) # Create example factor my_fac # Print example factor # [1] a b <NA> a c <NA> # Levels: a b c
The previous output of the RStudio console shows the structure of our example data: We have created a factor vector with the three factor levels a, b, and c. Furthermore, our factor contains some NA values (i.e. missing data).
Example: Turn NA into Extra Factor Level Using addNA() Function
In this example, I’ll demonstrate how to convert NA values to a new factor level using the addNA function in R.
Consider the R code below:
my_fac_NA <- addNA(my_fac) # Apply addNA function my_fac_NA # Print updated factor # [1] a b <NA> a c <NA> # Levels: a b c <NA>
Have a look at the previous output: It shows NA as additional factor level.
Video, Further Resources & Summary
Would you like to learn more about the application of the addNA function? Then you may watch the following video on my YouTube channel. I illustrate the examples of this article in the video.
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.
In addition, you may want to have a look at the related tutorials that I have published on this website. I have released numerous tutorials already:
- Convert Factor to Character Class
- na_if R Function of dplyr Package
- Convert Values in Column into Row Names of Data Frame
- Help – Warning: invalid factor level, NA generated
- Convert Factor to Dummy Indicator Variables for Every Level
- R Programming Overview
In this R programming tutorial you have learned how to apply the addNA function. If you have any additional questions, don’t hesitate to let me know in the comments section.
Statistics Globe Newsletter