Skip to content

Commit

Permalink
fix: Forbid reuse of new columns created in summarize()
Browse files Browse the repository at this point in the history
  • Loading branch information
krlmlr committed Mar 7, 2024
1 parent 89a727e commit 15d6810
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
18 changes: 16 additions & 2 deletions R/relational.R
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,19 @@ rel_try <- function(rel, ...) {
stop("Must use a return() in rel_try().")
}

rel_translate_dots <- function(dots, data) {
rel_translate_dots <- function(dots, data, forbid_new = FALSE) {
if (is.null(names(dots))) {
map(dots, rel_translate, data)
} else if (forbid_new) {
out <- accumulate(seq_along(dots), .init = NULL, function(.x, .y) {
new <- names(dots)[[.y]]
translation <- rel_translate(dots[[.y]], alias = new, data, names_forbidden = .x$new)
list(
new = c(.x$new, new),
translation = c(.x$translation, list(translation))
)
})
out[[length(out)]]$translation
} else {
imap(dots, rel_translate, data = data)
}
Expand All @@ -60,7 +70,8 @@ rel_translate <- function(
alias = NULL,
partition = NULL,
need_window = FALSE,
names_data = names(data)) {
names_data = names(data),
names_forbidden = NULL) {
if (is_expression(quo)) {
expr <- quo
env <- baseenv()
Expand All @@ -84,6 +95,9 @@ rel_translate <- function(
double = relexpr_constant(expr),
#
symbol = {
if (as.character(expr) %in% names_forbidden) {
abort(paste0("Can't reuse summary variable `", as.character(expr), "`."))
}
if (as.character(expr) %in% names_data) {
ref <- as.character(expr)
if (!(ref %in% used)) {
Expand Down
2 changes: 1 addition & 1 deletion R/summarise.R
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ summarise.duckplyr_df <- function(.data, ..., .by = NULL, .groups = NULL) {
}

groups <- lapply(by, relexpr_reference)
aggregates <- rel_translate_dots(dots, .data)
aggregates <- rel_translate_dots(dots, .data, forbid_new = TRUE)

if (oo) {
aggregates <- c(
Expand Down

0 comments on commit 15d6810

Please sign in to comment.