我正在寻找一种从另一数据帧填充数据帧的快速方法。为此,我想使用dplyr
包。例如,请考虑以下代码,它替换了dt2
中dt1
中的NA。我的目标是避免循环for
。
set.seed(123)
dt1 <- data.frame(ID = c(104, 109, 111, 121), a = c(1, 8, 5, 9), b = c(100, 220, 877, 120), c = c(1, 3, 2, 3))
## print(dt1)
dt2 <- data.frame(ID = c(rep(104, 1), rep(109, 3), rep(111, 2), rep(121, 3)),
a = c(rep(NA, 1), rep(NA, 3), rep(NA, 2), rep(NA, 3)),
b = c(rep(NA, 1), rep(NA, 3), rep(NA, 2), rep(NA, 3)))
## print(dt2)
for(i in as.vector(dt1[,c("ID")])) {
dt2[dt2[, c("ID")] %in% i, c("a")] <- sample(0:dt1[dt1[, c("ID")] == i, c("a")], size = dt1[dt1[, c("ID")] == i, c("c")], replace = T)
dt2[dt2[, c("ID")] %in% i, c("b")] <- sample(0:dt1[dt1[, c("ID")] == i, c("b")], size = dt1[dt1[, c("ID")] == i, c("c")], replace = T)
}
print(dt2)
输出为:
> print(dt2)
ID a b
1 104 0 79
2 109 3 10
3 109 7 116
4 109 8 197
5 111 3 840
6 111 2 398
7 121 6 108
8 121 5 29
9 121 1 5
这是我第一次使用dplyr
软件包进行测试:
set.seed(123)
dt1 <- data.frame(ID = c(104, 109, 111, 121), a = c(1, 8, 5, 9), b = c(100, 220, 877, 120), c = c(1, 3, 2, 3))
## print(dt1)
dt2 <- data.frame(ID = c(rep(104, 1), rep(109, 3), rep(111, 2), rep(121, 3)),
a = c(rep(NA, 1), rep(NA, 3), rep(NA, 2), rep(NA, 3)),
b = c(rep(NA, 1), rep(NA, 3), rep(NA, 2), rep(NA, 3)))
i <- 104
test <- dt2 %>%
mutate(a = replace(a, ID == i, sample(0:dt1[dt1[, c("ID")] == i, c("a")], size = dt1[dt1[, c("ID")] == i, c("c")], replace = T)),
b = replace(b, ID == i, sample(0:dt1[dt1[, c("ID")] == i, c("b")], size = dt1[dt1[, c("ID")] == i, c("c")], replace = T)))
print(test)
但是,我不知道如何考虑ID
,i.e., with i = 104, i = 109, i = 111, and i = 121
答案 0 :(得分:2)
我们可以使用left_join
,其中'dt1'由'ID',然后按'ID',transmute
,“ a”和“ b”列进行分组
left_join(dt2[1], dt1, by = "ID") %>%
group_by(ID) %>%
transmute(a = sample(0:a[1], size = c[1], replace = TRUE),
b = sample(0:b[1], size = c[1], replace = TRUE))
它也可以通过'df1'
完成dt1 %>%
rowwise() %>%
mutate_at(vars(a, b), funs(list(sample(0:., size = c, replace = TRUE)))) %>%
unnest %>%
select(-c)