合并两个数据帧并替换R中的NA值 [英] Merge two data frame and replace the NA value in R

查看:106
本文介绍了合并两个数据帧并替换R中的NA值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主表(a),其中包含列:id,年龄和性别.例如.

I have a main table(a), containing column: id, age, and sex. eg.

a <- data.frame(id=letters[1:4], age=c(18,NA,9,NA), sex=c("M","F","F","M"))
  id age sex
1  a  18   M
2  b  NA   F
3  c   9   F
4  d  NA   M

我有一个补充表(b),仅包含表(a)中所有丢失的数据或表(a)中重复的数据.例如.

And I have a supplement table(b), just containing all the missing data in table(a) or duplicated data in table(a). eg.

b <- data.frame(id=c("a","b","d"), age=c(18,32,20))
  id age
1  a  18
2  b  32
3  d  20

现在我要合并两个表,像这样:

Now I want to merge the two table, like this:

  id age sex
1  a  18   M
2  b  32   F
3  c   9   F
4  d  20   M

但是,我尝试了merge(a,b,by="id",all=T).结果不是我想要的.有什么办法可以解决这个问题?谢谢!

However, I'd tried merge(a,b,by="id",all=T). The result is not what I want. Is there any way to solve this problem? Thank you!

推荐答案

我们可以使用data.table

library(data.table)
setDT(a)[b, agei := i.age, on='id'][is.na(age), age := agei][,agei:= NULL][]
a
 #  id age sex
#1:  a  18   M
#2:  b  32   F
#3:  c   9   F
#4:  d  20   M

这篇关于合并两个数据帧并替换R中的NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆