r - 我可以让 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
但是,在我的情况下,如果表具有意外的公共列名,我希望连接中止并出现错误。有没有我可以提供给连接的选项,以便在连接之前有效地断言这个条件?还是我只需要在加入之前或之后手动检查它?
解决方案
我认为在连接之前检查未使用的重复列是最有意义的:
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
推荐阅读
- android - Android改变路径在画布中的位置
- google-chrome-devtools - Google Chrome Devtools 未正确显示亮点
- rust - 获取分区函数中项目的索引
- python - 将无效密码写入文本文件
- scala - 用于读取非常规日期格式的 Spark udf
- azure-data-factory - 我们如何将一个表映射到 Azure 数据工厂中 sink DB 中具有不同列的多个表?
- openlayers-3 - 开放层图中的 POI 和方向路径
- visual-studio - 在没有 VSTS 任务的情况下部署 BizTalk 应用程序项目 (.btaproj)
- ios - 无法在 ios 中接收来自 react-native-firebase 的通知消息
- firebase - 意外令牌 mailTransport firebase 云功能