Home > other >  R read target programmatically
R read target programmatically

Time:10-26

I have a set of targets, lets say data_a, data_b, ... I want to iterate over all datasets and load the data. This can be achieved using tar_read(data_a) or tar_read(data_a"). As I want to load the targets programmatically, I would like to use something like this in some kind of lapply:

target_name <- "data_a"
data <- tar_read(target_name)

But then I get the error that the target target_name was not found. I know this is related to NSE with R as tar_read internally calls substitute, but I wasn't able to figure out how to mask the target_name to make tar_read work. I have tried eval(parse()) and the different options presented in Advanced R, as well as rlang (such as !!, {{ and similar) to no avail.

Any idea how to achieve this?

CodePudding user response:

If you look at the code for tar_read, you see that it uses NSE to convert the name parameter into a character string, then calls the function tar_read_raw on the resulting string:

tar_read
#> function (name, branches = NULL, meta = tar_meta(store = store), 
#      store = targets::tar_config_get("store")) 
#> {
#>     force(meta)
#>     name <- tar_deparse_language(substitute(name))
#>     tar_read_raw(name = name, branches = branches, meta = meta, 
#>         store = store)
#> }

However, you can also use tar_read_raw directly. The manual for tar_read_raw says:

Like tar_read() except name is a character string.

So you should just be able to do:

data <- tar_read_raw(target_name)
  • Related