首页 > 解决方案 > 我可以让 dplyr 的连接函数对意外的重复变量抛出错误吗?

问题描述

当我inner_join在 dplyr 中执行操作时,如果两个表都有一个不在 in 中的公共列名by,它将使用suffix参数来消除名称的歧义:

> library(dplyr)
> table1 <- tibble(merge_key = letters, unintended_duplicate_col_name = LETTERS)
> table2 <- tibble(merge_key = letters, unintended_duplicate_col_name = seq_along(letters))
> inner_join(table1, table2, by = "merge_key", suffix = c(".1", ".2"))
# A tibble: 26 x 3
   merge_key unintended_duplicate_col_name.1 unintended_duplicate_col_name.2
   <chr>     <chr>                                                     <int>
 1 a         A                                                             1
 2 b         B                                                             2
 3 c         C                                                             3
 4 d         D                                                             4
 5 e         E                                                             5
 6 f         F                                                             6
 7 g         G                                                             7
 8 h         H                                                             8
 9 i         I                                                             9
10 j         J                                                            10
# … with 16 more rows

但是,在我的情况下,如果表具有意外的公共列名,我希望连接中止并出现错误。有没有我可以提供给连接的选项,以便在连接之前有效地断言这个条件?还是我只需要在加入之前或之后手动检查它?

标签: rjoindplyr

解决方案


我认为在连接之前检查未使用的重复列是最有意义的:

library(dplyr)

set.seed(5)
table1 <- setNames(data.frame(replicate(3, sample(letters))), c("a", "b", "c"))
table2 <- setNames(data.frame(replicate(3, sample(letters))), c("a", "b", "d"))
 
check_join <- function(x, y, by, ...) {
  stopifnot("Unexpected common column" = length(setdiff(intersect(names(x), names(y)), by)) == 0)
  inner_join(x, y, by, ...)
}


check_join(table1, table2, by = "a")

Error in check_join(table1, table2, by = "a") : Unexpected common column 

check_join(table1, table2, by = c("a", "b"))

  a b c d
1 f j i p
2 w i y s

推荐阅读