如何在R中使用dplyr进行条件连接?

3
例如,df1的样子如下 -
X1         X2     X3     X4         X5
Apple   Belgium   Red   Purchase   100 
Guava   Germany   Green Sale       200
Grape   Italy     Purple Purchase   500
Orange India   Orange   Sale       2000 

df2的样子如下 -

 X1         X2     X3     X4         X5
Apple   Belgium   Red   Purchase   10000 
Guava   Germany   Green Sale       20000
Grape   Italy     Purple Purchase   
Orange India   Orange   Sale       2000 

我的输出应该长这样 -
 X1         X2     X3     X4         X5.x  X5.y
Apple   Belgium   Red   Purchase   100     10000
Guava   Germany   Green Sale       200    20000
Grape   Italy     Purple Purchase   500   NA

这里涉及多个操作 -
1. 选择出只在其中一个表中而不在另一个中的行,反之亦然 2. 在第1到4列匹配的情况下,选择X5列中的不匹配项(X5是我的目标列) 3. 我不需要匹配的结果。
我尝试使用inner_join、full_join和anti_join的组合来获取part1。 我该如何执行第二部分? R中是否有可用的条件连接选项,仅选择不匹配项并忽略目标列相同时的情况?
我不想使用sqldf。 我知道可以在SQL中实现这一点。 我想在dplyr中完成此操作。非常感谢您的帮助。
2个回答

4
left_join(df1, df2, by = c("X1", "X2", "X3", "X4")) %>%
  filter(X5.x != X5.y | is.na(X5.x) | is.na(X5.y))
#      X1      X2     X3       X4 X5.x  X5.y
# 1 Apple Belgium    Red Purchase  100 10000
# 2 Guava Germany  Green     Sale  200 20000
# 3 Grape   Italy Purple Purchase  500    NA

在R中是否有条件连接可用,仅选择不匹配项,并忽略目标列相同时的情况?
是的,我认为您可以使用中的非等连接来实现此操作。或者使用您提到的。
我想在中执行此操作。 仅在相等性上进行连接。所以您需要先连接然后再过滤。
使用以下数据:
df1 = read.table(text = "X1         X2     X3     X4         X5
Apple   Belgium   Red   Purchase   100 
Guava   Germany   Green Sale       200
Grape   Italy     Purple Purchase   500
Orange India   Orange   Sale       2000", header = T)

df2 = read.table(text = "X1         X2     X3     X4         X5
Apple   Belgium   Red   Purchase   10000 
Guava   Germany   Green Sale       20000
Grape   Italy     Purple Purchase   NA
Orange India   Orange   Sale       2000", header = T)

你很棒。我已经明白了。谢谢你。 - Naive_Natural2511

1
(df1 
%>% anti_join(., df2, by = c("X1", "X2", "X3", "X4","X5")) 
%>% left_join(., df2, by = c("X1", "X2", "X3", "X4"))
)

    X1      X2     X3       X4 X5.x  X5.y
1 Apple Belgium    Red Purchase  100 10000
2 Guava Germany  Green     Sale  200 20000
3 Grape   Italy Purple Purchase  500    NA

我发现了fuzzy join这个包,可以用于“不精确匹配的数据框连接”。 - phili_b

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接