简体   繁体   English

R-替换数据帧中的NA

[英]R - Replacing NAs in a dataframe

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. 基本上,我想用第二列的值逐列替换第一个数据帧中的NA。 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 我正在考虑申请,但不确定如何有效地申请

You can easily combine these two dfs into one using coalesce from dplyr package. 您可以使用dplyr软件包中的coalesce功能轻松地将这两个dplyr coalesce为一个。

library(dplyr)

First df 第一个df

df <- data.frame(
  x1 = c(NA, NA, 3),
  x2 = c('Male', 'Female', NA),
  x3 = c(3, 7, 5)
)

Second df 第二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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM