Reputation: 744
I have a data frame with both quantitative and qualitative variables and contain many missing values
x1 x2 x3
NA Male 3
NA Female 7
3 NA 5
I also have another data frame
x1 x2 x3
3 Male NA
4 NA NA
NA NA NA
Basically I want to replace the NAs in the first data frame with values in the second data frame, column by column. My desire data set is
x1 x2 x3
3 Male 3
4 Female 7
3 Male 5
I am thinking about apply but not sure how to do it efficiently
Upvotes: 0
Views: 79
Reputation: 548
You can easily combine these two dfs into one using coalesce
from dplyr
package.
library(dplyr)
First df
df <- data.frame(
x1 = c(NA, NA, 3),
x2 = c('Male', 'Female', NA),
x3 = c(3, 7, 5)
)
Second df
df1 <- data.frame(
x4 = c(3, 4, NA),
x5 = c(NA, NA, 'Male'),
x6 = c(NA, NA, NA)
)
Solution:
df3 <- coalesce(df1, df2)
df3
# x1 x2 x3
#1 3 Male 3
#2 4 Female 7
#3 3 Male 5
Upvotes: 2