B.4 Metaprogramming
The R targets package includes metaprogramming tools (based on the rlang
package), that is, tools using code to generate code. One of the simpler cases is static branching, generating a number of branched targets over a series of varying parameters, e.g. using different methods of analysis or modelling, or changing an input parameter to the modelling function.
Full sets of targets (target factories) and full pipelines can also be generated on given parameters. These simplify the construction of a new targets pipeline, but is less customisable. See the stantargets package for an example of a target factory and [targets-shiny] for a fully-generated _targets.R
script with Shiny interface built on top.
An example of the pipeline-generating function resides in R/pipelines/write_pipeline_pm25_hia.R
. Here the global variables in the original targets.R
file are instead taken as arguments to the function. The targets pipeline code is written into the tar_helper
function (which writes out to the _targets.R
or other specified location). Variables (like states
and years
) are substituted into this code using the !!
operator which forces the evaluation of the following expression. (There is also a !!!
operator which both evaluates and unpacks, but it is not demonstrated here.)