【发布时间】:2021-02-27 22:25:59
【问题描述】:
.env 代词用于指代环境中的对象(而不是在 data.frame 中)在其他 dplyr 动词中效果很好,但在 slice_max 中返回错误。为什么?
考虑以下函数:
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
由reprex package (v0.3.0) 于 2020 年 11 月 16 日创建
【问题讨论】:
-
好点,@AllanCameron