Skip to content

Commit aa58fd6

Browse files
authored
env vignette explains that no extra work needed when using from outer function (#6939)
1 parent 5579977 commit aa58fd6

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

vignettes/datatable-programming.Rmd

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,29 @@ Users will usually want to substitute the function name rather than inserting th
389389

390390
In case of any doubts on the `env` interface functioning, set `verbose = TRUE` to inspect how expressions are resolved internally.
391391

392+
### Use `env` argument from inside another function
393+
394+
It was a design decision that `env` argument will follow _Standard Evaluation_ (SE) rules, i.e., values passed to `env` are evaluated in their original scope as-is. For more info on the topic see [R Language manual: Computing on the language](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Computing-on-the-language)). As a result, **using `env` argument from a function does not require any special handling**. It also means that the `.()` alias for a `list()`, _a la_ `env = .(.col="Petal.Length")`, will not work; use `env = list(.col="Petal.Length")` instead.
395+
396+
```{r env_se}
397+
fun = function(x, col.mean) {
398+
stopifnot(is.character(col.mean), is.data.table(x))
399+
x[, .(col_avg = mean(.col)), env = list(.col = col.mean)]
400+
}
401+
fun(DT, col.mean="Petal.Length")
402+
```
403+
404+
If the outer function itself follows NSE (Non-Standard Evaluation) rules, then it has to resolve language objects the same way as when passing its arguments to any other SE function.
405+
406+
```{r env_nse}
407+
fun = function(x, col.mean) {
408+
col.mean = substitute(col.mean)
409+
stopifnot(is.name(col.mean), is.data.table(x))
410+
x[, .(col_avg = mean(.col)), env = list(.col = col.mean)]
411+
}
412+
fun(DT, col.mean=Petal.Length)
413+
```
414+
392415
## Retired interfaces
393416

394417
In `[.data.table`, it is also possible to use other mechanisms for variable substitution or for passing quoted expressions. These include `get` and `mget` for inline injection of variables by providing their names as strings, and `eval` that tells `[.data.table` that the expression we passed into an argument is a quoted expression and that it should be handled differently. Those interfaces should now be considered retired and we recommend using the new `env` argument, instead.

0 commit comments

Comments
 (0)