r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
509 stars 138 forks source link

`rlang::.data` and `library(rlang); .data` work differently #1256

Closed logstar closed 3 years ago

logstar commented 3 years ago

rlang::.data and library(rlang); .data work differently, as following. It would be helpful to have a description on how to properly use .data and .env without running library(rlang) at https://rlang.r-lib.org/reference/tidyeval-data.html.

library(rlang); .data works:

# R version 4.1.0
> packageVersion("rlang")
[1] ‘0.4.11’
> library(rlang)
> a <- tibble::tibble(b = c(1,2,3), d = c(1,5,6))
> e <- 2
> d <- 3
> dplyr::filter(a, .data$b == 2)
# A tibble: 1 × 2
      b     d
  <dbl> <dbl>
1     2     5
> dplyr::filter(a, b == .env$e)
# A tibble: 1 × 2
      b     d
  <dbl> <dbl>
1     2     5

rlang::.data does not work:

> a <- tibble::tibble(b = c(1,2,3), d = c(1,5,6))
> e <- 2
> d <- 3
> dplyr::filter(a, rlang::.data$b == 2)
Error: Problem with `filter()` input `..1`.
ℹ Input `..1` is `rlang::.data$b == 2`.
✖ Input `..1` must be of size 3 or 1, not size 0.
Run `rlang::last_error()` to see where the error occurred.
> dplyr::filter(a, b == rlang::.env$e)
Error: Problem with `filter()` input `..1`.
ℹ Input `..1` is `b == rlang::.env$e`.
✖ Input `..1` must be of size 3 or 1, not size 0.
Run `rlang::last_error()` to see where the error occurred.

I am trying to use .data and .env without running library(rlang). The following way seems to work. But could there be any pitfalls without running library(rlang)?

> .data <- rlang::.data
> .env <- rlang::.env
> a <- tibble::tibble(b = c(1,2,3), d = c(1,5,6))
> e <- 2
> d <- 3
> dplyr::filter(a, .data$b == 2)
# A tibble: 1 × 2
      b     d
  <dbl> <dbl>
1     2     5
> dplyr::filter(a, b == .env$e)
# A tibble: 1 × 2
      b     d
  <dbl> <dbl>
1     2     5
lionel- commented 3 years ago

I've made it clearer in the documentation that rlang::.data should never be used in any actual code.