比较两个表并根据条件添加行 [英] Compare two table and adding row based on condition
问题描述
我想将 dt1 与 dt2 进行比较,使得如果 dt1 与 dt2 比较的列值存在,它不会添加行或更改该行中的值.因此,当值不同时(如示例中所示),其中 dt2 具有"4"& A列中的"5"将添加"4"& "5"到 dem1 表,但不会替换 dem1 中的"1","2"或"3"值列,因为它已经存在.
I would like to compare dt1 to dt2 such that if dt1 A column value exist when it compare to dt2 A column value it would not add a row or change the value in that row. So when the value are different like shown in the example where dt2 has "4" & "5" in A column it will add "4" & "5" to dt1 table but it would not replace it's "1", "2" or "3" value in dt1 A column since it existed already.
我想以主键的形式使用A列来检查以下内容:如果两个表的A列中都存在"1",则没有任何变化,但是如果存在A列值在 dt2 (例如:"4")中,但不在 dt1 中,那么我希望合并那一行数据与dt1表
I would like to use A column in a form of a primary key to check something along the line of if "1" exist in A column in both both table then nothing changes but if in there is a A column value in dt2(Example:"4") but not in dt1 then i wan that row of data to merge with dt1 table
dt1
A B C
1 4 7
2 5 8
3 6 9
dt2
A B C
1 10 13
2 12 15
3 11 14
4 1 20
5 12 3
dt1
A B C
1 4 7
2 5 8
3 6 9
4 1 20
5 12 3
推荐答案
您可以将dt1
绑定到dt2
中没有A
值的dt2
行中,只需一个条件语句
You can bind dt1
with rows from dt2
that don't have A
values in dt1
with just one conditional statement
rbind(dt1, dt2[!(dt2$A %in% dt1$A),])
# A B C
# 1 1 4 7
# 2 2 5 8
# 3 3 6 9
# 4 4 1 20
# 5 5 12 3
这篇关于比较两个表并根据条件添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!