假设两个数据集由公共列链接,我们称它们为“recipient”和“donor”。merge
可以使用(R) 或LEFT OUTER JOIN
(SQL)组合数据集。通常,在我的应用程序中,每个收件人记录都应该有一个(并且恰好是一个)匹配的捐助者记录。如果违反了这一点,则结果中会出现缺失值或重复的收件人记录。
问题
这个合并/连接操作是否有一个特殊的名称来强制执行这个额外的存在+唯一性约束?如果违反此约束,我希望合并/连接操作失败,因为在这种情况下,数据或生成数据的一些较早的代码有问题。
R函数示意图
enrich <- function(x, y, ...) {
xd <- deparse(substitute(x))
yd <- deparse(substitute(y))
stopifnot(!("..watchdog.." %in% colnames(y)))
y$..watchdog.. <- TRUE
res <- merge(x, y, sort = FALSE, all.x = TRUE, ...)
if (any(is.na(res$..watchdog..)))
stop("At least one row in x=", xd, " has no corresponding row in y=", yd)
if (nrow(res) > nrow(x))
stop("At least one row in x=", xd, " has duplicate corresponding rows in y=", yd)
res$..watchdog.. <- NULL
res
}
R 函数的结果
rec <- data.frame(id=letters[1:3], a=1)
don <- data.frame(id=letters[1:3], b=2)
enrich(rec, don)
## id a b
## 1 a 1 2
## 2 b 1 2
## 3 c 1 2
enrich(rec, don[1:2,])
## Error in enrich(rec, don[1:2, ]): At least one row in x=rec has no corresponding row in y=don[1:2, ]
enrich(rec, rbind(don, don))
## Error in enrich(rec, rbind(don, don)): At least one row in x=rec has duplicate corresponding rows in y=rbind(don, don)