Skip to content

Commit 71c874e

Browse files
nitish jhanitish jha
authored andcommitted
updating programming vignettee
1 parent 8297a4f commit 71c874e

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
@@ -373,6 +373,29 @@ print(j)
373373
DT[, j, env = list(j = j)]
374374
```
375375

376+
### Injecting functions using strings in `env`
377+
378+
In `data.table`, you can inject functions into your expressions by passing their names as strings in the `env` parameter. This method allows you to use function names directly as strings, and `data.table` will automatically interpret these strings as the corresponding functions. This approach simplifies the process and makes it easier to work with function names dynamically.
379+
380+
Suppose you want to calculate the total of `Sepal.Length` in the `iris` dataset using the `sum` function. You can inject the `sum` function by passing its name as a string in the `env` parameter.
381+
382+
```{r sum_example}
383+
result <- DT[, f(Sepal.Length), env = list(f = "sum")]
384+
print(result)
385+
```
386+
387+
In this example, the string `"sum"` is mapped to the `f` function. The `env` parameter allows `data.table` to recognize this `f` as the `sum` function, so it computes the total of `Sepal.Length` accordingly.
388+
389+
You can also inject multiple functions at once by specifying their names as strings in the `env` list. This is useful for performing various calculations within a single expression.
390+
391+
```{r multi_example}
392+
result <- DT[, .(total = f(Sepal.Length), average = d(Sepal.Length)),
393+
env = list(f = "sum", d = "mean")]
394+
print(result)
395+
```
396+
397+
In this example, both `"sum"` and `"mean"` are passed as strings. The `env` parameter maps these strings to their respective functions, allowing you to calculate both the total and the average of `Sepal.Length` in one go.
398+
376399
## Retired interfaces
377400

378401
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)