flowchart LR cf["cohort_file<br/>(file)"] --> c["cohort"] c --> m["m_main<br/>fit_main_model()"] c --> n["numbers<br/>make_numbers()"] m --> n c --> t["table_files<br/>make_tables()"] m --> t c --> f["figure_files<br/>make_figures()"]
3 Recompute Only What Changed with targets
In Chapter 2 we collected the model formula into a function in scripts/. Next we decide when, and in what order, those functions run. For this we use the R package targets.
3.1 Why targets?
If you compute everything inside the manuscript qmd, you run into these problems:
- Even when you fix a single sentence, every render recomputes all models, tables and figures
- A few seconds today becomes minutes per render once you add bootstrapping or multiple imputation
- It is hard to see “which data and which function produced this number”
With targets:
- The pipeline (data → model → numbers → tables and figures) is written in a single file,
_targets.R - Running
tar_make()recomputes only the parts affected by what changed - The manuscript just reads precomputed results, so rendering takes seconds
3.2 The whole _targets.R
Place it in the project root.
_targets.R
library(targets)
tar_option_set(packages = c("dplyr", "ggplot2", "gtsummary", "flextable"))
# Load the finalized processing (functions in scripts/)
tar_source(c("scripts/common/tables.R", "scripts/04_analysis", "scripts/05_output"))
sub_dir <- "output/submission"
list(
# Track the data file: if its contents change, everything downstream is recomputed
tar_target(cohort_file, "data/02_processed/cohort.rds", format = "file"),
tar_target(cohort, readRDS(cohort_file)),
# Main model (scripts/04_analysis/models.R)
tar_target(m_main, fit_main_model(cohort)),
# Numbers in the text (Chapter 4)
tar_target(numbers, make_numbers(cohort, m_main)),
# Tables and figures for submission (separate files)
tar_target(table_files, make_tables(cohort, m_main, sub_dir), format = "file"),
tar_target(figure_files, make_figures(cohort, sub_dir), format = "file")
)Each tar_target(name, computation) is a “target”. Using another target’s name inside a computation creates a dependency. For example, m_main is fit_main_model(cohort), so it depends on cohort.
3.2.1 What each part means
| Code | Meaning |
|---|---|
tar_option_set(packages = ...) |
Packages loaded before computing each target |
tar_source(...) |
Loads R files in scripts/ (a bulk version of source()). The functions inside are tracked too |
format = "file" |
Says the result is a “file path”; targets tracks whether the file’s contents changed |
tar_source()
scripts/common/ also contains files that “do something when run”, such as make_reference_docx.R, which rebuilds the Word template. If you pass the whole folder to tar_source(), it runs every time. Specify only files that just define functions.
3.3 Run it
Rscript -e 'targets::tar_make()'The first time, every target is computed.
+ cohort_file dispatched
✔ cohort_file completed [234ms, 8.46 kB]
+ cohort dispatched
✔ cohort completed [0ms, 8.46 kB]
+ figure_files dispatched
✔ figure_files completed [1s, 1.28 MB]
+ m_main dispatched
✔ m_main completed [1ms, 82.71 kB]
+ numbers dispatched
✔ numbers completed [43ms, 507 B]
+ table_files dispatched
✔ table_files completed [2.6s, 30.85 kB]
✔ ended pipeline [4s, 6 completed, 0 skipped]
Run it again without changing anything, and everything is skipped.
✔ skipped pipeline [38ms, 6 skipped]
3.4 Change a function, and only the affected parts are recomputed
Let’s remove diabetes from the formula in models.R.
fit_main_model <- function(cohort) {
glm(sarcopenia ~ physical_activity + age + sex + bmi, # diabetes removed
data = cohort, family = binomial)
}Running tar_make() gives:
✔ ended pipeline [3s, 3 completed, 3 skipped]
- Recomputed (3):
m_main, andnumbersandtable_files, which use it - Skipped (3):
cohort_file,cohort, andfigure_files, which does not use the model
targets remembers the body of each function and recomputes only the changed functions and whatever uses their results.
Editing only comments or whitespace inside a function does not trigger recomputation. targets compares the code by meaning (with comments stripped).
3.5 Reading results
| Function | Usage |
|---|---|
tar_read(numbers) |
Returns the result (assign it, e.g. num <- tar_read(numbers)) |
tar_load(m_main) |
Loads it as a variable of the same name (m_main becomes available) |
tar_outdated() |
Lists targets that need recomputation |
tar_manifest() |
Lists targets and their commands |
tar_visnetwork() |
Dependency graph (in the browser; needs visNetwork) |
analysis/ notebooks can read exactly the same results as the paper.
m_main_tar <- targets::tar_read(m_main) # instant if tar_make() has been run3.6 Common pitfalls
3.6.1 Rendering after forgetting tar_make()
If you fix a function but forget tar_make() before rendering the manuscript, it is built with the old numbers. To prevent this, this project checks tar_outdated() at the start of the manuscript and stops the render if any target is stale (Chapter 4).
! targets が古い: numbers, table_files, m_main
→ 先に Rscript -e 'targets::tar_make()'
(The sample project prints its messages in Japanese. This one means “targets are stale: numbers, table_files, m_main → run Rscript -e 'targets::tar_make()' first”.)
3.6.2 Data were replaced but nothing is recomputed
If you write tar_target(cohort, readRDS("data/02_processed/cohort.rds")), targets only sees the path string and never notices that the file’s contents changed. Make the file a format = "file" target and read from it (cohort_file → cohort above).
3.6.3 Table or figure files were deleted by hand
With format = "file", targets detects that a file was deleted or modified and rebuilds it on the next tar_make(). That is why make_tables() and make_figures() return the paths of the files they write.
make_figures <- function(cohort, out_dir) {
dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
save_fig(fig1(cohort), "Fig1", 17, 8, out_dir)
save_fig(fig2(cohort), "Fig2", 8.5, 8.5, out_dir)
file.path(out_dir, paste0(rep(c("Fig1", "Fig2"), each = 2), c(".tif", ".eps")))
}3.6.4 Don’t put the results folder _targets/ in git
_targets/ stores computed results (objects derived from the data). They may contain personal information, so add the folder to .gitignore.
3.7 Summary
- Write the pipeline in
_targets.R. Each target is a pair of “name” and “computation” tar_make()recomputes only the parts affected by changes- The manuscript and analysis notebooks just read results with
tar_read() - Track files with
format = "file"so their contents are monitored