我有一个数据框a
,缺少一些单元格的信息,我收集了丢失的数据,然后创建了另一个数据框b
。
通常我会通过以下代码填写缺失的数据:
for (loop.b in (1:nrow(b)))
{a[a[,"uid"]==b[loop.b,"uid"],"var1"] <- b[loop.b,"var1"]
}
这对我来说没问题,但如果b
有很多行怎么办?然后显式循环将使进程变慢。有没有更优雅的方式来做这种“缺少数据替换”的工作?
感谢。
答案 0 :(得分:1)
假设以下两个数据框与您描述的相似:
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
然后您可以直接使用以下内容:
R> a[b$uid,"var1"] <- b$var1
给出了:
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
答案 1 :(得分:1)
这有效:
# 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"]
答案 2 :(得分:0)
我认为您需要match
,但很难猜测您的数据是什么样的。
## 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
即使uids不是唯一的,它也会起作用(尽管名称有点暗示它们是)。