使用R中的merge填充data.frame中的NA

使用R中的merge填充data.frame中的NA,r,merge,R,Merge,我有一个数据框a缺少一些单元格的信息,我收集了缺少的数据,然后创建了另一个数据框b 通常我用以下代码填写缺失的数据: for (loop.b in (1:nrow(b))) {a[a[,"uid"]==b[loop.b,"uid"],"var1"] <- b[loop.b,"var1"] } (1:nrow(b))中的(loop.b)的 {a[a[,“uid”]==b[loop.b,“uid”],“var1”]我想你想要匹配,但很难猜测你的数据是什么样的 ## a's v

我有一个数据框
a
缺少一些单元格的信息,我收集了缺少的数据,然后创建了另一个数据框
b

通常我用以下代码填写缺失的数据:

for (loop.b in (1:nrow(b)))
    {a[a[,"uid"]==b[loop.b,"uid"],"var1"] <- b[loop.b,"var1"]
    }
(1:nrow(b))中的(loop.b)的


{a[a[,“uid”]==b[loop.b,“uid”],“var1”]我想你想要
匹配
,但很难猜测你的数据是什么样的

## a's var1 has some missing values
a <- data.frame(var1 = c(1, NA, 4.5, NA, 6.5), uid = 5:1)
## b knows all about them
b <- data.frame(var1 = c(2.3, 8.9), uid = c(2, 4))

## find the indexes in a$uid that match b$uid
ind <- match(b$uid, a$uid)

## those indexes now can be filled directly with b$uid
a$var1[ind] <- b$var1
##a的var1缺少一些值

a假设以下两个数据帧与您描述的相似:

R> a <- data.frame(uid=1:10,var1=c(1:3,NA,5:7,NA,9:10))
R> a
   uid var1
1    1    1
2    2    2
3    3    3
4    4   NA
5    5    5
6    6    6
7    7    7
8    8   NA
9    9    9
10  10   10

R> b <- data.frame(uid=c(8,4),var1=c(74,82))
R> b
  uid var1
1   8   74
2   4   82
这项工作:

# matches of a$uid in b$uid, NA if not match
ind = match(a$uid, b$uid) 
# 'ind' are the index in b and NA, we remove the latter
a[!is.na(ind),"var1"] = b[ind[!is.na(ind)],"var1"] 

看看
norm
软件包和
prelim.norm
函数。
Hmisc
有很好的插补功能,更不用说
mi
…CRAN软件包列表是一个很好的起点。哦,顺便说一句,摆脱那个讨厌的循环…=)我可能很密集,你能帮我发布一个小的可复制的例子吗?
R> a
   uid var1
1    1    1
2    2    2
3    3    3
4    4   82
5    5    5
6    6    6
7    7    7
8    8   74
9    9    9
10  10   10
# matches of a$uid in b$uid, NA if not match
ind = match(a$uid, b$uid) 
# 'ind' are the index in b and NA, we remove the latter
a[!is.na(ind),"var1"] = b[ind[!is.na(ind)],"var1"]