-
QuestionIf a global object depends on an external package, should it be wrapped by a function? For example, how do I incorporate a ggplot template into targets? Do I explicitly name the package (version 1) or wrap the list of plot components by a function (version 2), so that targets can figure out the dependency? A third alternative is to load all dependencies at the top (version 3), but this loses the speed advantage described in the user manual. Version 1library(targets)
common_coord <- list(ggplot2::coord_cartesian(xlim = c(1, 3)))
plot_vs_hp <- function(df) {
df %>%
ggplot(aes(x = wt, y = hp)) +
geom_point() +
common_coord
}
plot_vs_mpg <- function(df) {
df %>%
ggplot(aes(x = wt, y = mpg)) +
geom_point() +
common_coord
}
tar_option_set(packages = "tidyverse")
list(
tar_target(p_hp, plot_vs_hp(mtcars)),
tar_target(p_mpg, plot_vs_mpg(mtcars))
) Version 2# Version 2
library(targets)
common_coord <- function() {
list(coord_cartesian(xlim = c(1, 3)))
}
plot_vs_hp <- function(df) {
df %>%
ggplot(aes(x = wt, y = hp)) +
geom_point() +
common_coord()
}
plot_vs_mpg <- function(df) {
df %>%
ggplot(aes(x = wt, y = mpg)) +
geom_point() +
common_coord()
}
tar_option_set(packages = "tidyverse")
list(
tar_target(p_hp, plot_vs_hp(mtcars)),
tar_target(p_mpg, plot_vs_mpg(mtcars))
) Version 3# Version 3
library(targets)
library(tidyverse)
common_coord <- list(coord_cartesian(xlim = c(1, 3)))
plot_vs_hp <- function(df) {
df %>%
ggplot(aes(x = wt, y = hp)) +
geom_point() +
common_coord
}
plot_vs_mpg <- function(df) {
df %>%
ggplot(aes(x = wt, y = mpg)) +
geom_point() +
common_coord
}
tar_option_set(packages = "tidyverse")
list(
tar_target(p_hp, plot_vs_hp(mtcars)),
tar_target(p_mpg, plot_vs_mpg(mtcars))
) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Good question. Unless the object has brittle metadata (e.g. ropensci/drake#345) or system-dependent external pointers, I would recommend tracking the object as a global variable. That way, if you update the package where the object really lives, |
Beta Was this translation helpful? Give feedback.
Good question. Unless the object has brittle metadata (e.g. ropensci/drake#345) or system-dependent external pointers, I would recommend tracking the object as a global variable. That way, if you update the package where the object really lives,
targets
will invalidate the object and the appropriate downstream targets. If you wrap the object in a function, thentargets
will track the deparsed code to generate the object instead of the object itself. That means unless you calltar_option_set(imports = "ggplot2")
(which seems cumbersome for your use case) updating the package will not invalidate the object.