As mentioned in my other answer dplyr::cur_data_all()
should be an alternative which works instead of .data
. I have not yet seen a case where cur_data_all()
doesn't work inside data-masking dplyr verbs, but .data
does. We can also access grouping variables, which doesn't work with 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
However, outside of dplyr verbs cur_data_all()
cannot be used, while .data
will work depending on the context. This is the case in tibble
s for example:
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.
Although cur_data()
and cur_data_all()
throw an error saying they can only be used inside dplyr verbs this is only half true. They can only be used inside data-masking dplyr verbs. However, this also holds true for .data
which won't work in verbs supporting tidy selection:
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.
Created on 2021-12-23 by the reprex package (v0.3.0)