Basil
Basil

Reputation: 1004

Using targets with dataframes in a list

I am struggling to use the targets package with lists.

In my _targets.R file I have:

library(targets)
library(tidyverse)
# load functions
source("R/functions.R")

list(
  tar_target(name = file, "data.csv", format = "file"),
  tar_target(name = raw_data, command = get_data(file))
)

When I run tar_visnetwork() in the console, I get the network chart in the viewer as expected.

However when I change the code to reflect that the data is actually in a list called raw_data, I get the error message: Last error: raw_data$data is not a valid symbol name. so does this mean I can't use lists with the targets package or is the code incorrect?

library(targets)
library(tidyverse)
# load functions
source("R/functions.R")

list(
  tar_target(name = file, "data.csv", format = "file"),
  tar_target(name = raw_data$data, command = get_data(file))
)

Upvotes: 0

Views: 125

Answers (1)

Greg
Greg

Reputation: 3326

Per the documentation for the name argument to tar_target():

A target name must be a valid name for a symbol in R, and it must not start with a dot.

So raw_data and data are each a valid symbol, but raw_data$data is an extraction operation and is thus invalid.


Perhaps you can create an environment like exe_env, and run your workflow in it, before pulling the results into a list? I can't reproduce your functions.R script or your data.csv dataset, so this is merely an abstract suggestion.

library(targets)
library(tidyverse)

# load "rlang" for expressions
library(rlang)

# load custom functions
source("R/functions.R")


# define execution environment
exe_env <- new.env()

# run workflow in that environment
exprs(
  tar_target(name = file, "data.csv", format = "file"),
  tar_target(name = data, command = get_data(file))
) |>
  lapply(eval, envir = exe_env)

# pull results into list
raw_data <- as.list(exe_env)


# examine results
raw_data$file
raw_data$data

Upvotes: 1

Related Questions