Create a function like dplyr::n() that can see the .data argument

Is it possible to create custom functions similar to dplyr::n() that can see the .data argument?

For example, in dplyr::summarise(mtcars, n()) the function n() can (presumably) see mtcars so that it can count the number of rows.

I have explored rlang::env_parent() and others, but the trouble is that the parent environment is always the global environment, not the environment of dplyr::summarise().

foo <- function() {
  print(rlang::env_parent())
  1
}
dplyr::summarise(mtcars, n())
#>   n()
#> 1  32
dplyr::summarise(mtcars, foo())
#> <environment: R_GlobalEnv>
#>   foo()
#> 1     1

Is there any other way to access the environment of dplyr::summarise() (or similar) from within foo()?

Created on 2018-12-18 by the reprex package (v0.2.0.9000).

1 Like

You can not currently.

2 Likes

The Man himself has spoken on the environment question. What beyond counting rows are you looking for?

> nrow(dplyr::summarise(mtcars, n()))
[1] 1

because, in fact, there's not much there there

> str(dplyr::summarise(mtcars, n()))
'data.frame':	1 obs. of  1 variable:
 $ n(): int 32
> 

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.