Skip to content

Commit

Permalink
Improve .data and .env translation
Browse files Browse the repository at this point in the history
Fixes #138
  • Loading branch information
hadley committed Dec 24, 2019
1 parent a69dd3f commit 7544de4
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# dtplyr (development version)

* Better handling for `.data` and `.env` pronouns (#138).

* dplyr verbs now work with `NULL` inputs (#129).

* `lazy_dt()` objects now have a useful `glimpse()` method (#132).
Expand Down
4 changes: 3 additions & 1 deletion R/step.R
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ as.data.frame.dtplyr_step <- function(x, ...) {
#' @export
#' @importFrom tibble as_tibble
as_tibble.dtplyr_step <- function(x, ...) {
as_tibble(dt_eval(x))
out <- as_tibble(dt_eval(x))
attr(out, ".internal.selfref") <- NULL
out
}

#' @export
Expand Down
14 changes: 14 additions & 0 deletions R/tidyeval.R
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,20 @@ dt_squash <- function(x, env, vars, j = TRUE) {
} else if (is_quosure(x)) {
dt_squash(get_expr(x), get_env(x), vars = vars, j = j)
} else if (is_call(x)) {
# Handle .env and .data
if (is_call(x, c("$", "[["), n = 2)) {
var <- x[[3]]
if (is_call(x, "[[")) {
var <- sym(eval(var, env))
}

if (is_symbol(x[[2]], ".data")) {
return(var)
} else if (is_symbol(x[[2]], ".env")) {
return(sym(paste0("..", var)))
}
}

if (is_call(x, "n", n = 0)) {
quote(.N)
} else if (is_call(x, "row_number", n = 0)) {
Expand Down
12 changes: 12 additions & 0 deletions tests/testthat/test-tidyeval.R
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ test_that("can access functions in local env", {
expect_equal(dt %>% summarise(n = f()) %>% pull(), 100)
})

test_that("can disambiguate using .data and .env", {
dt <- lazy_dt(data.frame(x = 1))
x <- 2

out <- dt %>% summarise(data = .data$x, env = .env$x) %>% as_tibble()
expect_equal(out, tibble(data = 1, env = 2))

var <- "x"
out <- dt %>% summarise(data = .data[[var]], env = .env[[var]]) %>% collect()
expect_equal(out, tibble(data = 1, env = 2))
})

# dplyr verbs -------------------------------------------------------------

test_that("n() is equivalent to .N", {
Expand Down

0 comments on commit 7544de4

Please sign in to comment.