str_replace_na Function in R Programming (Example)
In this article, I’ll show how to replace NA values with str_replace_na in R programming.
The post will contain these content blocks:
- Constructing Example Data
- Example 1: Default Application of str_replace_na Function in R
- Example 2: Manual Replacement with str_replace_na Function
- Video, Further Resources & Summary
Let’s take a look at some R codes in action!
Constructing Example Data
As a first step, we have to create a vector of character strings. This vector also needs to contain some NA values:
x <- c("aaa", NA, "bb", "abc", NA) # Create vector of character strings
In order to use the str_replace_na command, we also need to install and load the stringr add-on package of the R programming language:
install.packages("stringr") # Install stringr package library("stringr") # Load stringr package
Example 1: Default Application of str_replace_na Function in R
The example data is set up and the stringr package is loaded. Now, we can apply the str_replace_na function as follows:
str_replace_na(x) # Apply str_replace_na function # "aaa" "NA" "bb" "abc" "NA"
At first sight, the output looks similar. However, have a look at the quotation marks that are surrounding the NAs (i.e. “NA” instead of NA).
This actually means that the missing values in our vector of character strings were converted to character strings themselves.
Example 2: Manual Replacement with str_replace_na Function
We can also replace the NA values in our vector by different values than “NA”. We simply need to specify the replacement argument as shown below:
str_replace_na(x, replacement = "xxx") # Different replacement # "aaa" "xxx" "bb" "abc" "xxx"
As you can see, each NA value was replaced by the pattern “xxx”.
Video, Further Resources & Summary
I have recently released a video on my YouTube channel, which illustrates the R code of this tutorial. You can find the video below.
The YouTube video will be added soon.
Furthermore, you may read some of the other tutorials on this homepage. You can find a selection of tutorials here:
- Replace NA with 0
- Replace NA with Last Observed Value
- R na_if Function of dplyr Package
- What are NA Values in R?
- R Functions List (+ Examples)
- The R Programming Language
In this tutorial, I showed how to replace missing values in the R programming language. Let me know in the comments section, in case you have further questions. In addition, don’t forget to subscribe to my email newsletter to get updates on new articles.