The .env
pronoun used to refer to objects in an environment (as opposed to inside a data.frame) works well inside other dplyr verbs but returns an error in slice_max
. Why?
Consider the following functions:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(rlang)
f1 <- function(y) {
d <- tibble(x = runif(20))
d %>%
slice_max(order_by = .data$x, n = .env$y)
}
f2 <- function(y) {
d <- tibble(x = runif(20))
d %>%
filter(.data$x >= .env$y)
}
f3 <- function(y) {
d <- tibble(x = runif(20))
d %>%
mutate(z = .env$y)
}
f1(2)
#> Error: `n` must be a single number.
f2(0.8)
#> # A tibble: 8 x 1
#> x
#> <dbl>
#> 1 0.936
#> 2 0.812
#> 3 0.998
#> 4 0.962
#> 5 0.901
#> 6 0.875
#> 7 1.00
#> 8 0.919
f3(2)
#> # A tibble: 20 x 2
#> x z
#> <dbl> <dbl>
#> 1 0.0318 2
#> 2 0.928 2
#> 3 0.983 2
#> 4 0.622 2
#> 5 0.583 2
#> 6 0.0314 2
#> 7 0.481 2
#> 8 0.791 2
#> 9 0.476 2
#> 10 0.599 2
#> 11 0.468 2
#> 12 0.234 2
#> 13 0.276 2
#> 14 0.382 2
#> 15 0.914 2
#> 16 0.736 2
#> 17 0.572 2
#> 18 0.863 2
#> 19 0.337 2
#> 20 0.515 2
Created on 2020-11-16 by the reprex package (v0.3.0)