diff --git a/NEWS.md b/NEWS.md index 657ae5306..6ee454045 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # dbplyr (development version) +* `slice_*()` now supports the data masking pronouns `.env` and `.data` (@mgirlich, #1294). + * `tbl()` now informs when the user probably forgot to wrap the table identifier with `in_schema()` or `sql()` (@mgirlich, #1287). diff --git a/R/verb-slice.R b/R/verb-slice.R index f3af9545a..b72eb9c06 100644 --- a/R/verb-slice.R +++ b/R/verb-slice.R @@ -163,7 +163,8 @@ slice_by <- function(.data, order_by, size, .by, with_ties = FALSE) { # must use `add_order()` as `window_order()` only allows variables # this is only okay to do because the previous, legal window order is restored - .data$lazy_query <- add_order(.data, quos({{order_by}})) + dots <- partial_eval_dots(.data, !!!quos({{order_by}}), .named = FALSE) + .data$lazy_query <- add_order(.data, dots) out <- filter(.data, !!window_fun) %>% window_order(!!!old_frame) diff --git a/tests/testthat/_snaps/verb-slice.md b/tests/testthat/_snaps/verb-slice.md index a9c564c90..4660c4685 100644 --- a/tests/testthat/_snaps/verb-slice.md +++ b/tests/testthat/_snaps/verb-slice.md @@ -66,6 +66,39 @@ ! `na_rm = FALSE` isn't supported on database backends. i It must be TRUE instead. +# slice_* can use data masking pronouns + + Code + lf %>% slice_max(x) + Output + + SELECT `x`, `id` + FROM ( + SELECT `df`.*, RANK() OVER (ORDER BY `x` DESC) AS `q01` + FROM `df` + ) AS `q01` + WHERE (`q01` <= 1) + Code + lf %>% slice_max(.data$x) + Output + + SELECT `x`, `id` + FROM ( + SELECT `df`.*, RANK() OVER (ORDER BY `x` DESC) AS `q01` + FROM `df` + ) AS `q01` + WHERE (`q01` <= 1) + Code + lf %>% slice_max(.data$x * .env$x) + Output + + SELECT `x`, `id` + FROM ( + SELECT `df`.*, RANK() OVER (ORDER BY `x` * -1 DESC) AS `q01` + FROM `df` + ) AS `q01` + WHERE (`q01` <= 1) + # slice_sample errors when expected Code diff --git a/tests/testthat/test-verb-slice.R b/tests/testthat/test-verb-slice.R index 9768dd338..770a6b20a 100644 --- a/tests/testthat/test-verb-slice.R +++ b/tests/testthat/test-verb-slice.R @@ -28,6 +28,17 @@ test_that("slice_max orders in opposite order", { expect_snapshot(error = TRUE, db %>% slice_max(id, n = 1, na_rm = FALSE)) }) +test_that("slice_* can use data masking pronouns", { + lf <- lazy_frame(x = c(1, 1, 2), id = c(1, 2, 3)) + x <- -1L + + expect_snapshot({ + lf %>% slice_max(x) + lf %>% slice_max(.data$x) + lf %>% slice_max(.data$x * .env$x) + }) +}) + test_that("slice_sample errors when expected", { db <- memdb_frame(x = c(1, 1, 2), id = c(1, 2, 3))