You can use the coalesce() function from the dplyr package in R to return the first non-missing value in each position of one or more vectors.
There are two common ways to use this function:
Method 1: Replace Missing Values in Vector
library(dplyr)
#replace missing values with 100
coalesce(x, 100)
Method 2: Return First Non-Missing Value Across Data Frame Columns
library(dplyr)
#return first non-missing value at each position across columns A and B
coalesce(df$A, df$B)
The following examples show how to each method in practice.
Example 1: Use coalesce() to Replace Missing Values in Vector
The following code shows how to use the coalesce() function to replace all missing values in a vector with a value of 100:
library(dplyr)
#create vector of values
x #replace missing values with 100
coalesce(x, 100)
[1] 4 100 12 100 5 14 19
Notice that each NA value in the original vector has been replaced with a value of 100.
Example 2: Use coalesce() to Return First Non-Missing Value Across Data Frame Columns
Suppose we have the following data frame in R:
#create data frame
df frame(A=c(10, NA, 5, 6, NA, 7, NA),
B=c(14, 9, NA, 3, NA, 10, 4))
#view data frame
df
A B
1 10 14
2 NA 9
3 5 NA
4 6 3
5 NA NA
6 7 10
7 NA 4
The following code shows how to use the coalesce() function to return the first non-missing value across columns A and B in the data frame:
library(dplyr)
#create new column that coalesces values from columns A and B
df$C
#view updated data frame
df
A B C
1 10 14 10
2 NA 9 9
3 5 NA 5
4 6 3 6
5 NA NA NA
6 7 10 7
7 NA 4 4
The resulting column C contains the first non-missing value across columns A and B.
Notice that row 5 has a value of NA in column C since columns A and B both had NA values in that row.
We can simply add one more value to the coalesce() function to use as the value if there happen to be NA values in each column:
library(dplyr)
#create new column that coalesces values from columns A and B
df$C
#view updated data frame
df
A B C
1 10 14 10
2 NA 9 9
3 5 NA 5
4 6 3 6
5 NA NA 100
6 7 10 7
7 NA 4 4
Notice that the NA value in row 5 of column C has now been replaced by a value of 100.
Additional Resources
The following tutorials explain how to perform other common functions using dplyr:
How to Remove Rows Using dplyr
How to Arrange Rows Using dplyr
How to Filter by Multiple Conditions Using dplyr