tidyverse / dtplyr

Data table backend for dplyr
https://dtplyr.tidyverse.org
Other
664 stars 58 forks source link

Data pronoun `.env` fails in `i` position functions #450

Open markfairbanks opened 1 year ago

markfairbanks commented 1 year ago
library(dtplyr)
library(dplyr, warn.conflicts = FALSE)

x <- 3

dt <- lazy_dt(tibble(x = 1:3, y = 1:3))

# Works
dt %>%
  mutate(x_x = .data$x * .env$x)
#> Source: local data table [3 x 3]
#> Call:   copy(`_DT1`)[, `:=`(x_x = x * ..x)]
#> 
#>       x     y   x_x
#>   <int> <int> <dbl>
#> 1     1     1     3
#> 2     2     2     6
#> 3     3     3     9
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

# Fails
dt %>%
  filter(.data$x < .env$x)
#> Error: Object '..x' not found amongst [x, y]

This one is going to be a tough one since the .. shortcut doesn't work in i

markfairbanks commented 1 year ago

I think the easiest solution is to wait until the newest version of data.table is on CRAN and we can use the new env arg.

suppressMessages(library(data.table))

df <- data.table(x = 1:3, y = 1:3)

x <- 3

df[x < .env_x, env = list(.env_x = x)]
#>        x     y
#>    <int> <int>
#> 1:     1     1
#> 2:     2     2
markfairbanks commented 1 year ago

We could probably just even detect if .env is used and do something like this.

suppressMessages(library(data.table))

df <- data.table(x = 1:3, y = 1:3)

x <- 3

df[x < .env$x, env = list(.env = environment())]
#>        x     y
#>    <int> <int>
#> 1:     1     1
#> 2:     2     2