Skip to content

Commit

Permalink
Clean error if summarising summarised variable
Browse files Browse the repository at this point in the history
Fxies #75
  • Loading branch information
hadley committed Jul 3, 2019
1 parent 0c70adf commit f2ae6a5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
17 changes: 17 additions & 0 deletions R/step-subset.R
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ select.dtplyr_step <- function(.data, ...) {
#' @export
summarise.dtplyr_step <- function(.data, ...) {
dots <- capture_dots(.data, ...)
check_summarise_vars(dots)

if (length(dots) == 0) {
if (length(.data$groups) == 0) {
Expand Down Expand Up @@ -261,3 +262,19 @@ simplify_names <- function(vars) {
names(vars)[vars == names(vars)] <- ""
vars
}

# For each expression, check if it uses any newly created variables
check_summarise_vars <- function(dots) {
for (i in seq_along(dots)) {
used_vars <- all_names(get_expr(dots[[i]]))
cur_vars <- names(dots)[seq_len(i - 1)]

if (any(used_vars %in% cur_vars)) {
abort(paste0(
"`", names(dots)[[i]], "` ",
"refers to a variable created earlier in this summarise().\n",
"Do you need an extra mutate() step?"
))
}
}
}
5 changes: 5 additions & 0 deletions tests/testthat/test-step-subset.R
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ test_that("empty summarise returns unique groups", {
)
})

test_that("if for unsupported resummarise", {
dt <- lazy_dt(data.frame(x = 1:3, y = 1:3))
expect_error(dt %>% summarise(x = mean(x), x2 = sd(x)), "mutate")
})

# select/rename ------------------------------------------------------------------

test_that("renames grouping vars", {
Expand Down

0 comments on commit f2ae6a5

Please sign in to comment.