---
title: "Start here"
author: "John Ehrlinger"
vignette: >
  %\VignetteIndexEntry{Start here}
  %\VignetteEngine{quarto::html}
  %\VignetteEncoding{UTF-8}
format:
  html:
    toc: true
    embed-resources: true
---

If you are new to the HVTI R family, or new to a study, read this page first.
The work comes in two parts, and the order matters. `hvtiR` gets the study
ready, once. The `hvtiRtemplates` tutorials then take you through the analysis,
every day after that.

## What you need

You need a session on the server, the study's directory, and its title and ID
from Study Tracker. On Posit Workbench, start a new RStudio Pro session and pick
the latest R version listed. The family requires R 4.4.0 or newer, and `setup()`
stops on anything older.

A study that already has a `renv.lock` is the exception: pick the R version its
`R` `Version` entry records. `setup()` only warns about a different one, and its
snapshot then records the R you are running. `upgrade = FALSE` keeps package
versions from moving, not R.

## Where to type

Every R command on this page goes in RStudio's **Console** pane, at the `>`
prompt, one command at a time. Press Enter to run it. The **Terminal** tab beside
the Console is a shell, not R, and an R command typed there fails. The page has
one shell command, `study-setup --verify`, and it says so where it comes.

- Text after a `#` is a comment. R ignores it, so you can paste it or leave it out.
- `EDIT:` marks a value that is yours to fill in. Replace the words, and keep the
  quotation marks around them.
- A command can run over several lines. Paste it whole: R waits, showing `+`
  instead of `>`, until the closing parenthesis arrives.
- `hvtiR::setup()` means "the `setup()` function from the `hvtiR` package". The
  page writes every call that way so that it works in a fresh session.
  [Common errors](#common-errors) explains why.

## Coming back to a study {#coming-back}

A study you have worked on before holds `_study.yml` and `renv.lock` in its top
directory. `_study.yml` is the study's identity and settings: its title and
Study Tracker ID, and where its data and reports live, so every job reads them
from one place. `renv.lock` records the version of every package the study
declares, so the analysis can be rerun with the same ones. A package a job
uses but the study never declared is not recorded:
[Adding a package](study-environment.html#adding-a-package) shows how to
declare it. Do not run
`hvtiR::setup()` on the study again: setup is once per study. Each time you
come back, work through these steps in order.

1. **Open the study's `.Rproj`** (**File > Open Project**). Every command below
   runs inside it. A `setup()` run from inside one project, with `root` naming
   another study, stops: it would install into the open project's library.

2. **Ask the family whether you are current.** `status()` compares each family
   package installed in the study with the latest version on GitHub:

   ```r
   hvtiR::status()
   ```

   It prints one line per package, then what to do. When the installer and
   some packages are behind, the end looks something like this:

   ```
   ! hvtiR 1.3.1 is behind 1.3.8 on GitHub.
   ℹ Update the installer with `pak::pak("ehrlinger/hvtiR")`.
   ℹ 11 members need updating. Run hvtiR::update().
   ```

3. **Run what its last lines print.** When the installer is behind, they name
   `pak::pak("ehrlinger/hvtiR")`. Run that first, then restart R
   (**Session > Restart R**). When members are behind, they say
   `Run hvtiR::update()`. Run it as

   ```r
   hvtiR::update(force = TRUE)
   ```

   and restart R again. `force = TRUE` installs over a member that is already
   loaded, and the restart is what makes R use the new copy. On Windows that
   is unsafe: restart R first and run `hvtiR::update()` without it.

4. **Record your update, or restore the study's.** After you updated packages
   in step 3, record what the library now holds:

   ```r
   renv::snapshot()
   ```

   When renv says the project is out of sync and you updated nothing, the
   lockfile is the record to trust: someone else may have updated the study, or
   this machine's library is behind it. Do not snapshot. Run `renv::status()`,
   and when it lists packages that the lockfile records but the library lacks,
   or holds at other versions, bring the library back to the lockfile:

   ```r
   renv::restore()
   ```

   When renv itself needs updating, the command is `renv::upgrade()`. The names
   are easy to mix up: `renv::update()` updates the packages in the study's
   library, not renv. [A study's package environment](study-environment.html#updating-packages)
   has the details.

5. **Record rebuilt data.** When the built datasets have been rebuilt under the
   same file names since you last worked, record the new versions:

   ```r
   hvtiRutilities::update_manifest()
   ```

   Each registered dataset whose file changed gets a new dated version, and jobs
   read that version from then on. Unchanged datasets are left alone. To update
   one dataset only, name it:

   ```r
   hvtiRutilities::update_manifest(dataset = "built")
   ```

   Do not pass the file with `file =` to do this: naming a file switches
   `update_manifest()` to registering that one file as a new source.

6. **Upgrade a job to its template's current version.** If the job is open in
   the editor, save it and close it first. `upgrade_job()` reads the file on
   disk, so edits you have not saved are left out of the upgrade, and saving
   the old copy afterwards would overwrite it.

   Name the job's `.qmd` file from the study's top directory. Type the opening
   quotation mark and press Tab: RStudio completes the folder and file names
   for you.

   ```r
   hvtiRtemplates::upgrade_job("10_descriptive/dc.general.cohort.eda.qmd")  # EDIT: your job
   ```

   The upgrade keeps the old job, and a report of the chunks to check, in the
   `_archive` folder beside it. Open the upgraded job, check the chunks the
   report names, then render it and follow it:

   ```r
   hvtiRtemplates::run_job("10_descriptive/dc.general.cohort.eda.qmd")     # EDIT: your job
   hvtiRtemplates::job_status("10_descriptive/dc.general.cohort.eda.qmd")  # EDIT: your job
   ```

7. **Add a job the study does not have yet.** List the templates, or browse
   what each one produces in the
   [template gallery](https://ehrlinger.github.io/hvtiRtemplates/gallery/):

   ```r
   hvtiRtemplates::template_list()
   ```

   Then add one. `subject` and `type` are yours to choose: they name the job,
   and every job of one analysis shares them.

   ```r
   hvtiRtemplates::add_job("dc.eda", subject = "cohort", type = "eda")  # EDIT: your template and names
   ```

   The job is written into its template's folder, here `10_descriptive/`.
   Open it, fill in its `EDIT:` lines, and run it as in step 6.
   [Work a job, from template to final report](https://ehrlinger.github.io/hvtiRtemplates/articles/work-a-job.html)
   walks through the whole loop.

[Check the study](#check-the-study) explains what `status()` and
`study_status()` report.

## Has the study been set up already?

Look in the study's directory. If it holds both `_study.yml` and `renv.lock`,
someone has probably set it up: open its `.Rproj`, then go to
[Check the study](#check-the-study). If you set it up and are returning to it,
see [Coming back to a study](#coming-back). Those two files can also come from an older
`renv::init()`, which brings neither the family nor the standard packages. If
`hvtiR::status()` there shows members missing, run `setup()` there to adopt
it, as [If the study already has a library](#from-outside)
describes.

A new study may have been set up when its directory was made, because the
`study-setup` command in `qhsprograms` runs `hvtiR::setup()` for you. Otherwise,
carry on here.

## Set up the study

Most studies already have a directory, with folders and files of their own.
Set one of those up from inside it, as an RStudio project. A study whose
directory does not exist yet is set up from outside;
[A new directory](#a-new-directory) covers that case.

### What adopting deletes

Setting up an existing directory is called adopting it. Adopting deletes four
kinds of file anywhere in the study, and makes no backup:

- every file whose name starts with `tp.`, **matched by name alone**, so an edited
  or study-specific `tp.*` file goes too;
- every `binder.summaries.doc`;
- every `config.fixtemplates`, the legacy fixtemplates step's settings, also
  matched by name alone;
- every other file whose name and exact content match one in the template corpus.

Before you adopt, look through the study for `tp.*` files that hold work of your
own, and rename or copy any you need. To adopt without deleting anything, add
`cleanup = FALSE` to the call below.

### Open the study as a project

If the study's top directory holds a `.Rproj` file, open it (**File > Open
Project**). If it has none, make one: **File > New Project > Existing
Directory**, then browse to the study's top directory and click
**Create Project**.

Choose the top directory, the one that holds the study's folders, not one of
those folders. `setup()` refuses a folder named like a study folder, such as
`datasets` or `30_analyses`, and names the directory above it to open instead.

### Run it

In the Console, install the installer, then set the study up:

```r
install.packages("pak")  # once per machine
pak::pak("ehrlinger/hvtiR")

hvtiR::setup(
  study = "EDIT: the Study Tracker title",
  study_tracker_id = 0L,  # EDIT: the Study Tracker ID
  identity_source = "manual"
)
```

The call names no directory: `setup()` takes the project you have open. Because
that directory has no `_study.yml` yet, it asks before changing anything:

```
/path/to/study has no _study.yml. Adopt it as study "..." (Study Tracker ...)?
Adopting deletes the tp.* files, binder.summaries.doc, config.fixtemplates and
exact template copies it holds; pass cleanup = FALSE to keep them. (Yes/no/cancel)
```

Check the directory, title and ID in the question, then press Enter. The
answer it shows in capitals, `Yes`, is what pressing Enter alone gives, so read
the question first: adopting deletes the files it names. `no` or `cancel` prints
`Not adopted. Nothing was changed.`, and nothing was.

`identity_source = "manual"` is there because you typed the title and ID. The
default says they came from a Study Tracker record, and a new `_study.yml` would
then record them as verified. A `_study.yml` the study already has is not rewritten.

A study in revision needs one more argument, `upgrade = FALSE`. By default,
`setup()` moves a version the lockfile pins when the family needs a newer one,
and lists each move. In revision those versions must not move, so with
`upgrade = FALSE` a package the install would move stops the run instead, and
`renv.lock` stays as it was.

### If the study already has a library {#from-outside}

A study that already has a package library of its own, from an older
`renv::init()`, loads that library when you open the project. `setup()` replaces
packages in it, which it cannot do from a session that has them loaded. So it
installs nothing in this session. After you answer `yes` if it asked, it runs
itself again in a fresh R session started outside any project, and prints that
session's output in the Console:

```
ℹ Running `setup()` in a fresh R session outside the project.
```

When the study already has a `_study.yml`, it first asks here, because the
fresh session cannot:

```
/path/to/study already has a _study.yml. Adopt it, adding what is missing?
Adopting deletes the tp.* files, binder.summaries.doc, config.fixtemplates and
exact template copies it holds; pass cleanup = FALSE to keep them. (Yes/no/cancel)
```

Press Enter, or type `yes`: Yes is the default. Adopting deletes the files listed in
[What adopting deletes](#what-adopting-deletes), as it does for a first setup.
To keep them, add `cleanup = FALSE` to the call. When the
fresh session finishes, the project reopens on the study's library.

The fresh session needs `hvtiR` in your own library. If it is installed only in
a study's library, `setup()` stops before installing anything and prints the
call to run instead:

```
Run it from a session started outside any project: hvtiR::setup(root = "...", ...)
```

Close the project (**File > Close Project**). Check that
`Sys.getenv("RENV_PROJECT")` prints `""`, install the installer with
`pak::pak("ehrlinger/hvtiR")`, then paste the call it printed into the Console.

### A new directory {#a-new-directory}

For a study whose directory does not exist yet, close any open project, then
name the directory with `root`:

```r
hvtiR::setup(
  study = "EDIT: the Study Tracker title",
  study_tracker_id = 0L,  # EDIT: the Study Tracker ID
  root = "EDIT: the study directory",
  identity_source = "manual"
)
```

`setup()` creates the directory with the numbered folders (`00_datasets`,
`10_descriptive` and so on). An adopted study keeps the folder names it has.

### An exploration of a registered study {#an-exploration}

Sometimes the work starts before Study Tracker has a record for it: a question
that grew out of a registered study and may become a study of its own. Set it
up with `derived_from`, the registered study's ID, in place of
`study_tracker_id`:

```r
hvtiR::setup(
  study = "Lactate trajectories (exploration)",
  derived_from = 1234L,  # EDIT: the registered study's ID
  root = "EDIT: the study directory",
  identity_source = "manual"
)
```

Give one ID or the other, never both. The study gets a provisional ID, and
`study_status()` shows its `_study.yml` as `EXPLORATORY`. Checkpoints are made
and kept on your machine, but none is pushed until the study has an ID of its
own. Once Study Tracker registers it, record that ID from inside the project:

```r
hvtiRutilities::study_promote(5678L)  # EDIT: the new Study Tracker ID
```

`study_promote()` keeps `derived_from` as the study's lineage. When the study
has a checkpoint repository, it also records a checkpoint of the promotion.
The checkpoints held until then become pushable: they reach the study's
remote, when it has one, the next time a push gets through.

### What it does

In order, `setup()`:

- turns off RStudio's `.RData` restore and save, for you rather than for the
  study (`workspace_prefs = FALSE` leaves them alone);
- writes the study's identity to `_study.yml`, adding a project file when there
  is none, and deletes the files listed above if you are adopting;
- declares `hvtiR`, every family member and the standard analysis packages in
  the study's `DESCRIPTION`;
- installs them into the study's own library and records them in `renv.lock`;
- checks that every package's dependencies resolve there;
- restarts RStudio inside the project (outside RStudio, it tells you to restart
  R there).

It needs no data, so you can run it at kick-off. It needs no personal GitHub
token to install, either, since pak carries a shared one. It warns when you have
none, because restoring a package a lockfile already pins on GitHub may need your
own `GITHUB_PAT`.

If it stops partway, fix what it names and run the same command again. Each step
checks before it acts, so a rerun is safe.

### When it worked

The last step restarts RStudio inside the study. The project name in RStudio's
top right corner is the study's directory name, and the Files pane shows
`_study.yml` and `renv.lock` beside the study's folders. Go on to
[Check the study](#check-the-study).

If R printed an error instead, read the message from its first line: it names
what stopped the run. Fix that and run the same `hvtiR::setup()` command again.

### What not to run

Do not run `renv::init()` on the study: `setup()` has already made the
environment, and `renv::init()` starts the library over. Do not run
`organize_templates.sh`: `setup(adopt = TRUE)` replaces it. When a study needs
a package the family and the standard set do not bring, add it from inside the
project:

```r
hvtiRutilities::study_need("cmprsk")
```

That installs it, declares it and records it in `renv.lock`. A package already
installed is only declared, so run `renv::snapshot()` after it.
[A study's package environment](study-environment.html) covers updates, revisions
and what to do when the environment misbehaves.

## Check the study {#check-the-study}

Now you are inside the project. Ask the study what it still needs, and the
family whether you are current:

```r
hvtiRutilities::study_status()
hvtiR::status()
```

`study_status()` prints a checklist, one line per thing a study needs: `[x]`
marks one that is in place, `[ ]` one that is not, and `[~]` one that is in
place but not yet confirmed. On a study set up as above, `renv.lock` is ticked
and `_study.yml` shows `[~]`. You typed the title and ID
(`identity_source = "manual"`), so the line says they were entered by hand and
to confirm them with `study-setup --verify`.

That is a shell command, so it goes in RStudio's **Terminal** tab, not the
Console. Run it from the study's directory:

```sh
study-setup --verify
```

It looks the ID up in Study Tracker and compares the title you typed. When they
match, it marks the identity verified, and `study_status()` then shows `[x]` for
`_study.yml`. When they differ, it lists each difference and asks whether to
take Study Tracker's values; answer no and nothing changes. A study that the
`study-setup` command created was read from Study Tracker in the first place, so
its `_study.yml` shows `[x]` from the start.

The `manifest.yaml` and `dataset` lines are not ticked either, and each says to
run `register_data()`. That is expected: registering the data is the next step,
and it belongs to the tutorials. `hvtiR::status()`
reports whether each family package in the study is current, and how to update
any that are not.

## Go on to the tutorials

From here the work moves to
[`hvtiRtemplates`](https://ehrlinger.github.io/hvtiRtemplates/).

1. **Register the data.** For a new study,
   [Start a new study](https://ehrlinger.github.io/hvtiRtemplates/articles/new-study.html).
   For an existing one,
   [Adopt an existing study](https://ehrlinger.github.io/hvtiRtemplates/articles/study-setup.html).
2. **Work a job.**
   [Work a job, from template to final report](https://ehrlinger.github.io/hvtiRtemplates/articles/work-a-job.html)
   is the daily loop: pick a template, add it, fill in its `EDIT:` lines, render,
   and read the report.
3. **Choose the next template.** The
   [template gallery](https://ehrlinger.github.io/hvtiRtemplates/gallery/) shows
   what each one produces on a synthetic study.

If you are coming from SAS,
[From SAS descriptive jobs to R](https://ehrlinger.github.io/hvtiRtemplates/articles/sas-to-r-descriptive.html)
sets the descriptive templates beside the `tp.dc.*` jobs they replace.

## Try the family without a study {#scratch}

`install()` and `update()` refuse to install into your personal library, and
they say so. They accept any renv project, though, so to test the family, or a
package branch against it, without touching a study, make a scratch project:

```r
dir <- file.path(
  path.expand("~"),
  paste0("hvtiR-scratch-", format(Sys.time(), "%Y%m%d-%H%M%S"))
)
stopifnot(dir.create(dir))   # a new folder, never one that exists
renv::init(dir, bare = TRUE, restart = FALSE)
renv::load(dir)              # active now, in RStudio or a terminal
dir                          # note it: later sessions need it
```

Then install hvtiR and pak into the empty library, and the family after them:

```r
renv::install(c("pak", "ehrlinger/hvtiR"))
hvtiR::install()
```

The folder is new and dated, so it holds nothing but the scratch project.
`dir.create()` returns `FALSE` for a folder that already exists, and
`stopifnot()` stops there rather than going on into it.

Don't count on a restart to activate the project. In a terminal,
`renv::init()` asks you to restart R and leaves this session on your personal
library. Where renv's autoloader is turned off, a restart doesn't activate it
either. `renv::load()` works in both cases. In a later session, run
`renv::load()` with the folder you noted.

Keep the folder out of `tempdir()`, which R deletes when the session ends.
On lri, use your home directory, not a study share.

When you are done, quit that session. From a new session, delete the folder
you noted, and only that folder:

```r
unlink("~/hvtiR-scratch-20261123-134500", recursive = TRUE)   # your folder
```

Your personal library is never touched, and no study's lockfile moves.

## Common errors {#common-errors}

R's error messages are terse. These are the ones new users of the family meet
most, word for word as R prints them, with what each means.

### `could not find function "read_built"`

```
Error in read_built() : could not find function "read_built"
```

R knows a function only once its package is attached, and a new session
attaches none of the family. Either name the package in the call, as this page
does:

```r
d <- hvtiRutilities::read_built()
```

or attach the package once per session, then call the function by its name:

```r
library(hvtiRutilities)
d <- read_built()
```

Attaching lasts until R restarts, and `hvtiR::setup()` restarts it, so attach
again afterwards. The functions you will use most come from three packages:

| Package          | Functions                                                           |
|------------------|---------------------------------------------------------------------|
| `hvtiR`          | `setup()`, `status()`, `update()`, `doctor()`                       |
| `hvtiRutilities` | `register_data()`, `read_built()`, `study_status()`, `study_need()` |
| `hvtiRtemplates` | `add_job()`, `job_status()`, `run_job()`, `upgrade_job()`           |

### `'package' must be of length 1`

```
Error in library(c("hvtiRutilities", "hvtiRtemplates")) :
  'package' must be of length 1
```

`library()` attaches one package per call. To attach all three at once:

```r
invisible(lapply(c("hvtiR", "hvtiRutilities", "hvtiRtemplates"), library, character.only = TRUE))
```

### `The following object is masked from ‘package:stats’: update`

This is a note, not an error, printed when `library(hvtiR)` attaches. It means
that `update()` now runs `hvtiR::update()`, which updates the family. To update a
fitted model, write `stats::update(fit, ...)`.

### `there is no package called ‘cmprsk’`

```
Error in library(cmprsk) : there is no package called ‘cmprsk’
```

Each study has a library of its own, and that package is not in this one, even
if another study or your own library has it. From inside the study's project,
install it into the study:

```r
hvtiRutilities::study_need("cmprsk")
```

When the missing package is one of the family, run `hvtiR::status()` instead.

### `no _study.yml found`

```
Error: study_config(): no _study.yml found.
```

R is working outside the study. A study function finds its study by looking for
`_study.yml` in the working directory and each folder above it, and the message
lists every folder it looked in. Open the study's `.Rproj` file, or run
`getwd()` to see where R is, and try again.

## When something goes wrong

Start with the doctor:

```r
hvtiR::doctor()
```

It reports your R version, your platform, whether pak is available, the
repositories R is configured to use and whether an renv project is active, and
[Install, update and check the family](hvtiR.html#when-something-will-not-install)
explains the failures we see most. If that does not settle it, tell the team.
Send the code you ran, what you expected, what happened instead, and the
doctor's output. A failure you hit is usually a gap in the tools or in this page,
so report it early.

Never send patient data. Column names and `dim()` are fine; rows are not.
