正如我在其他answer 中提到的,dplyr::cur_data_all() 应该是替代.data 的替代方案。我还没有看到cur_data_all() 不起作用在数据屏蔽 dplyr 动词中,但 .data 起作用的情况。我们还可以访问分组变量,这不适用于cur_data():
library(dplyr)
mtcars %>%
group_by(cyl) %>%
transmute(x = cur_data()[["cyl"]],
y = .data[["cyl"]],
z = cur_data_all()[["cyl"]])
#> # A tibble: 32 x 3
#> # Groups: cyl [3]
#> cyl y z
#> <dbl> <dbl> <dbl>
#> 1 6 6 6
#> 2 6 6 6
#> 3 4 4 4
#> 4 6 6 6
#> 5 8 8 8
#> 6 6 6 6
#> 7 8 8 8
#> 8 4 4 4
#> 9 4 4 4
#> 10 6 6 6
#> # … with 22 more rows
但是,在 dplyr 之外的动词 cur_data_all() 不能使用,而 .data 将根据上下文起作用。例如tibbles 就是这种情况:
library(dplyr)
tibble(new = 1,
new2 = .data$new)
#> # A tibble: 1 x 2
#> new new2
#> <dbl> <dbl>
#> 1 1 1
tibble(new = 1,
new2 = cur_data_all()$new)
#> Error in context_peek("mask", fun): `cur_data_all()` must only be used inside dplyr verbs.
虽然cur_data() 和cur_data_all() 抛出一个错误,说它们只能在dplyr 动词中使用,但这只是对了一半。它们只能在 data-masking dplyr 动词中使用。但是,这对于 .data 也适用,它不适用于支持整齐选择的动词:
library(dplyr)
mtcars %>%
select(6)
#> wt
#> Mazda RX4 2.620
#> Mazda RX4 Wag 2.875
#> Datsun 710 2.320
#> Hornet 4 Drive 3.215
#> Hornet Sportabout 3.440
#> Valiant 3.460
...
mtcars %>%
select(first(.data$cly)) # should be 6 the same as above
#> Error in stop_fake_data_subset(): Can't subset `.data` outside of a data mask context.
mtcars %>%
select(first(cur_data_all()$cly)) # should be 6 the same as above
#> Error in context_peek("mask", fun): `cur_data_all()` must only be used inside dplyr verbs.
由reprex package (v0.3.0) 于 2021 年 12 月 23 日创建