2  Try It in analysis, Move It to scripts

“Try things in analysis, and once it looks right, move it to scripts” is hard to picture from words alone, so let’s walk through it day by day.

As an example, consider examining the association between physical activity and sarcopenia with logistic regression, starting from deciding which covariates to adjust for.

2.1 Day 1: try various things in analysis

Create analysis/2026-11-20_model_explore.qmd and try whatever models come to mind, written inline.

```{r}
#| label: setup
source(here::here("scripts/common/utils.R"))   # load shared settings (packages, paths)
cohort <- readRDS(file.path(processedDataDir, "cohort.rds"))
```

## Try 1: adjust for age only

```{r}
m1 <- glm(sarcopenia ~ physical_activity + age, data = cohort, family = binomial)
broom::tidy(m1, exponentiate = TRUE, conf.int = TRUE)
```

## Try 2: add sex and BMI

```{r}
m2 <- glm(sarcopenia ~ physical_activity + age + sex + bmi, data = cohort, family = binomial)
broom::tidy(m2, exponentiate = TRUE, conf.int = TRUE)
```

## Try 3: also add diabetes  <- go with this one

```{r}
m3 <- glm(sarcopenia ~ physical_activity + age + sex + bmi + diabetes,
          data = cohort, family = binomial)
broom::tidy(m3, exponentiate = TRUE, conf.int = TRUE)
```

Everything so far lives in analysis/. It can be messy.

2.2 Day 2: “Let’s go with Try 3!” → move it to scripts

2.2.1 ① Write it in scripts as a function

Write the formula from Try 3 as a function in scripts/04_analysis/models.R.

scripts/04_analysis/models.R
# Main models (only what was tried and decided in analysis/ goes here)
# Keeping a change log here (what and why) makes it easy to check against the Methods later
#   2026-11-22 adopted "Try 3" from analysis/2026-11-20_model_explore.qmd as the main model

fit_main_model <- function(cohort) {
  glm(sarcopenia ~ physical_activity + age + sex + bmi + diabetes,
      data = cohort, family = binomial)
}

2.2.2 ② Delete the inline code in analysis and call the function instead

This is the most important step. Move, don’t copy. Delete the inline glm(...) on the analysis/ side and replace it with a call to the function.

analysis/2026-11-22_model_main.qmd
```{r}
#| label: setup
source(here::here("scripts/common/utils.R"))
source(here::here("scripts/04_analysis/models.R"))   # <- open the toolbox
cohort <- readRDS(file.path(processedDataDir, "cohort.rds"))
```

## Main model

```{r}
m_main <- fit_main_model(cohort)                     # <- instead of the inline glm(...)
broom::tidy(m_main, exponentiate = TRUE, conf.int = TRUE)
```

The formula is identical, so the result is exactly the same as Try 3 on Day 1.

2.2.3 ③ Call the same function from the paper

The paper side (_targets.R in Chapter 3) calls the same fit_main_model().

tar_target(m_main, fit_main_model(cohort))

Now the model formula exists in exactly one place in the whole project: models.R.

2.3 Day 5: your supervisor says “add smoking too”

Fix only that one place in models.R.

scripts/04_analysis/models.R
fit_main_model <- function(cohort) {
  glm(sarcopenia ~ physical_activity + age + sex + bmi + diabetes + smoking,
      data = cohort, family = binomial)
}
  • Re-running the analysis/ notebook gives the result with smoking
  • Rebuilding the paper updates the ORs in the text, the numbers in the abstract and Table 2 all automatically

2.4 What if you had copy-pasted instead of using scripts

flowchart LR
  subgraph bad["Copy-paste"]
    A1["analysis qmd<br/>glm(... + diabetes + smoking)"]
    M1["main.qmd<br/>glm(... + diabetes)  ← forgot to update"]
  end
  subgraph good["Moved to scripts"]
    S2["models.R<br/>fit_main_model()"]
    A2["analysis qmd"] --> S2
    M2["main.qmd"] --> S2
  end

With copy-paste, glm(...) is written in both the analysis qmd and the paper. Forget to update one of them when adding smoking, and you get “the OR is 0.34 in analysis but 0.38 in the paper… why?” This is the same kind of mismatch as the painful “double-checking Excel against R”.

2.5 What is source()?

source() is a function that runs another R file in its entirety.

source(here::here("scripts/04_analysis/models.R"))

When you run this, the contents of models.R are executed from top to bottom, and the functions defined inside it (fit_main_model) become available right there.

  • models.R = a toolbox
  • source() = open the toolbox and lay the tools out on your desk
  • fit_main_model(cohort) = use a tool

How it differs from library():

Function What it loads
library(dplyr) An installed package
source("file.R") An R file you wrote yourself
TipWhy use here::here()

Writing source("scripts/04_analysis/models.R") makes the path relative to the “current folder”. Depending on whether the qmd is run from inside analysis/ or from the project root, the file may not be found.

here::here("scripts/04_analysis/models.R") builds the path from the project root (the folder containing .here or .Rproj), so it points to the same file no matter where you run it from.

2.6 How much to move into scripts

Move to scripts Keep in analysis
Preprocessing (in scripts from the start, as in Chapter 1) Models you tried and discarded
The main models Plots for checking
Tables and figures for the paper Notes on “why this model”
Numbers that appear in the text (Chapter 4) Drafts before showing your supervisor

2.7 If you want to change a function later

If you don’t want results in old analysis notebooks to change, add an argument whose default keeps the old behaviour.

fit_main_model <- function(cohort, covars = c("age", "sex", "bmi", "diabetes")) {
  f <- reformulate(c("physical_activity", covars), response = "sarcopenia")
  glm(f, data = cohort, family = binomial)
}

fit_main_model(cohort)                                 # same as before
fit_main_model(cohort, covars = c("age", "sex"))       # sensitivity analysis

Don’t worry too much if old analysis notebooks stop working. They are records of exploration and can be disposable (Chapter 6 shows how to keep their results).

2.8 Summary

  • Try in analysis → once decided, move it to scripts as a function
  • Delete the inline code in analysis and replace it with a function call (don’t copy)
  • analysis and the paper call the same function, so the numbers never diverge
  • Changes are made in one place in scripts