targets-r-package

object not found when creating targets list programmatically


I'm trying to generate a {targets} list programmatically, via a function in an R package.

get_pipeline <- function(which_countries) {
  countries <- NULL # avoid R CMD CHECK warning
  print(which_countries) # Shows that which_countries is available
  list(
    targets::tar_target(
      name = countries,
      command = which_countries # But here, which_countries is not found
    )
  )
}

The _targets.R file looks like this:

library(targets)
couns <- c("USA", "GBR")
TargetsQuestions::get_pipeline(couns)

I see the following error:

> tar_make()
[1] "USA" "GBR"
Error in enexpr(expr) : object 'which_countries' not found
Error in `tar_throw_run()`:
! callr subprocess failed: object 'which_countries' not found

Note that the which_countries variable is printable, but not found in the call to tar_target.

How can I get create the countries target successfully so that it contains the vector c("USA", "GBR")?

This code is in a GitHub repository at https://github.com/MatthewHeun/TargetsQuestions. To reproduce:

Thanks in advance for any suggestions!


Solution

  • Thanks to @landau for pointing to https://wlandau.github.io/targetopia/contributing.html#target-factories which in turn points to the metaprogramming section of Advanced R at https://adv-r.hadley.nz/metaprogramming.html.

    The solution turned out to be:

    get_pipeline <- function(which_countries) {
      list(
        targets::tar_target_raw(
          name = "countries",
          # command = which_countries # which_countries must have length 1
          # command = !!which_countries # invalid argument type
          command = rlang::enexpr(which_countries) # Works
        )
      )
    }
    

    With _targets.R like this:

    library(targets)
    couns <- c("USA", "GBR")
    TargetsQuestions::get_pipeline(couns)
    

    the commands tar_make() and tar_read(countries), give

    [1] "USA" "GBR"
    

    as expected!