msm1089
msm1089

Reputation: 1504

Why is the output different when I run examples from https://rpubs.com/hadley/dplyr-programming

I'm trying to understand NSE with dplyr, using the article in the title.

I find I am getting different outputs for some examples. Could anyone explain why?

Example 1

The functional form (of !!, i.e. UQ) is useful in cases where the precedence of ! causes problems:

my_fun <- quo(fun)
quo(!!my_fun(x, y, z))
#> Error in (function (x) : could not find function "my_fun"
quo(UQ(my_fun)(x, y, z))
#> ~(~fun)(x, y, z)

gives me

my_fun <- quo(fun)
quo(!!my_fun(x, y, z))
# Error in my_fun(x, y, z) : could not find function "my_fun"
quo(UQ(my_fun)(x, y, z))
# <quosure>
# expr: ^`~`(fun)(x, y, z)
# env:  global

Example 2

A very useful feature of unquote-splicing is that the vector names become argument names: ... This makes it easy to program with dplyr verbs that take named dots:

args <- list(mean = ~mean(cyl), count = ~n())
mtcars %>%
  group_by(am) %>%
  summarise(!!! args)
#> # A tibble: 2 × 3
#>      am     mean count
#>   <dbl>    <dbl> <int>
#> 1     0 6.947368    19
#> 2     1 5.076923    13

gives me this error

Error in `summarise()`:
ℹ In argument: `mean = ~mean(cyl)`.
ℹ In group 1: `am = 0`.
Caused by error:
! `mean` must be a vector, not a <formula> object.
Run `rlang::last_trace()` to see where the error occurred.

but it does work when I use quo rather than the formula syntax (~)

args <- list(mean = quo(mean(cyl)), count = quo(n()))
mtcars %>%
  group_by(am) %>%
  summarise(!!! args)
#> # A tibble: 2 × 3
#>      am     mean count
#>   <dbl>    <dbl> <int>
#> 1     0 6.947368    19
#> 2     1 5.076923    13

Relevant session info is:

R version 4.3.3 (2024-02-29 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server 2019 x64 (build 19045)

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] dplyr_1.1.4

Upvotes: 3

Views: 64

Answers (0)

Related Questions