我有一个数据帧fp,例如
Item Date Quantity
I1 Jun 1202
I1 Jul 1290
I1 Aug 1829
I1 Sep 1710
I2 Jun 892
I2 Jul 910
I2 Aug 791
我有这个集合的逐项子集,我需要对其进行一些更新,例如fpItem
Item Date Quantity
I1 Jun 1202
I1 Jul 1300
I1 Aug 1900
我想将更新后的子集(fpItem)中的行替换为原始数据帧fp,例如
Item Date Quantity
I1 Jun 1202
I1 Jul 1300
I1 Aug 1900
I2 Jun 892
I2 Jul 910
I2 Aug 791
有相同的建议吗?
答案 0 :(得分:2)
您可以这样做:
library(dplyr)
df %>%
left_join(df_subset, by = c("Item", "Date")) %>%
group_by(Item) %>%
filter(!(is.na(Quantity.y) & any(!is.na(Quantity.y)))) %>%
mutate(Quantity = coalesce(Quantity.y, Quantity.x)) %>%
select(-matches("\\.x|\\.y"))
输出:
# A tibble: 6 x 3
# Groups: Item [2]
Item Date Quantity
<chr> <chr> <int>
1 I1 Jun 1202
2 I1 Jul 1300
3 I1 Aug 1900
4 I2 Jun 892
5 I2 Jul 910
6 I2 Aug 791