coalesce R Function of dplyr Package (2 Examples)
In this article you’ll learn how to apply the coalesce function of the dplyr add-on package in R programming.
The table of content looks as follows:
- Example 1: Use coalesce Function to Replace Missing Values with One Value
- Example 2: Match Two Vectors with coalesce Function
- Video, Further Resources & Summary
If you want to know more about these contents, keep reading!
Example 1: Use coalesce Function to Replace Missing Values with One Value
install.packages("dplyr") # Install and load dplyr package library("dplyr")
Furthermore, we need to create some example data:
x <- c(2, 1, NA, 5, 3, NA) # Create example vector
Our example data is a numeric vector with two NA values.
Now, we can use the coalesce function to replace these NA values by a different value. In this example, we are replacing the NA values with the number 999:
coalesce(x, 999) # Apply coalesce function # 2 1 999 5 3 999
As you can see based on the output of the RStudio console, our updated vector contains the value 999 at each NA position.
Example 2: Match Two Vectors with coalesce Function
We can also use the coalesce command to merge two numeric vectors into one vector. Let’s first create a second vector:
y <- c(1, NA, 7, NA, 7, NA) # Create second example vector
Note that our second vector also contains missing values.
Now, we can match our two vectors x and y as follows:
coalesce(x, y) # Match two vectors # 2 1 7 5 3 NA
As you can see, the coalesce command replaced each missing value of x with the corresponding value in y. Note that the last vector element is still NA, since both input vectors contain an NA value at this position.
Video, Further Resources & Summary
Do you need more info on the dplyr package? Then you could watch the following video of my YouTube channel. In the video, I’m explaining other functions of the dplyr package in RStudio:
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.
Additionally, I can recommend to read the other articles of this website.
- Replace NA with Last Observed Value
- Replace NA with 0
- What are
- is.na Function
- How to Remove NA Values From Vector
- Introduction to dplyr
- R Functions List (+ Examples)
- The R Programming Language
Summary: In this R programming tutorial you learned how to replace NA values with the coalesce dplyr function. If you have further questions, don’t hesitate to let me know in the comments.
Statistics Globe Newsletter