Package 'pbn'

Title: House Layout and Checks for Analysis Projects
Description: Holds the house layout of a versioned analysis project and the checks of that layout. It runs the real data and fake scenarios as one 'plnr' plan, with a seed for each simulation, writes one results object for each scenario and simulation with a fixed contract, checks the fake scenarios against their expected values, and computes the numbers of a descriptive table. It checks the bias, the standard error and the coverage of an estimate over the simulations of a fake scenario against limits from their Monte Carlo standard errors (Morris, White and Crowther, 2019, <doi:10.1002/sim.8086>).
Authors: Richard Aubrey White [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-6747-1726>)
Maintainer: Richard Aubrey White <[email protected]>
License: MIT + file LICENSE
Version: 2026.12.20
Built: 2026-12-03 09:17:17 UTC
Source: https://github.com/raubreywhite/pbn

Help Index


Add one analysis for each scenario and simulation to a plan

Description

add_analyses() adds the analysis kind name to the plnr plan p: one analysis for each scenario and simulation of scenarios, and for each combination of the extra dimensions in ....

Usage

add_analyses(p, scenarios, name, fn, ..., control = FALSE)

Arguments

p

A plan from plnr::Plan$new().

scenarios

The scenarios of the run, from scenarios().

name

The name of the analysis kind, for example "models". It is the name of the element of the results object. It MUST be a syntactic name that starts with a letter. It MUST NOT be "manifest" or "exclusions", and it MUST NOT start with "pbn_". Each kind of one plan MUST have its own name. save_results() names the exclusion table of a cohort exclusions.

fn

The action function, ⁠function(data, argset)⁠.

...

The extra dimensions, each named, for example outcome = CFG$outcomes. Each MUST be an atomic vector with at least one value, with no NA and no value twice. A vector of length 1 is a constant of the kind.

control

TRUE adds the kind to every fake scenario of scenarios, and never to "real". Use it for a check that is not a result, for example a model without adjustment that a fake scenario tests.

Details

Each analysis gets the name ⁠<scenario>__sim_<kkkk>__<name>__<i>⁠, for example null__sim_0003__models__2. ⁠<kkkk>⁠ is the simulation with four digits, also for a scenario with 1 simulation. ⁠<i>⁠ counts the combinations of the extra dimensions from 1, with the last dimension of ... changing fastest. A kind without extra dimensions has ⁠<i>⁠ 1. To step through one analysis by hand, use get_argset() and get_data(). They take the scenario, the simulation, the kind and ⁠<i>⁠, so you do not type the name.

The argset of each analysis holds these fields:

  • scenario, sim, and analysis, the kind name.

  • seed, the seed of the analysis.

  • the value of each extra dimension.

  • the value of each setting column of its scenario.

The name of an extra dimension MUST follow these rules:

  • It MUST be syntactic.

  • It MUST NOT be the name of a setting column.

  • It MUST NOT be one of scenario, sim, analysis, seed, index_analysis, name, fn, fn_name, data and argset.

pbn adds fn in a wrapper. The wrapper calls set.seed(argset$seed) and then fn(data, argset). fn runs inside the wrapper, so plnr::is_run_directly() is FALSE in it when the plan runs.

The seed depends on the kind name, the counter ⁠<i>⁠ and sim only:

  • It does not depend on the order of the analyses, the worker count or the R session.

  • Two kinds of one simulation get different seeds, so they draw different numbers.

  • One kind gets the same seed in each scenario, so its draws in null and in real of one simulation are the same.

  • It is 10000 or more, so it differs from the seed sim of the data of simulations 1 to 9999.

The seed is 10000 + h %% 2147473629. h is a polynomial hash with base 257, modulo the prime 2147483629, of the code points of "<name>__<i>__<sim>". Two analyses of one simulation with the same seed stop add_analyses() with an error that names both kinds.

While run_plan() runs, an analysis fails when it changes the shared data in place. plnr gives every analysis of one scenario and simulation the same object, so a later analysis in the same R session would get the changed data. pbn compares two things before and after each analysis:

  • the names, the number of rows, the data.table key and the address of each column of each data.frame. This finds an added, removed, renamed or replaced column, for example data$d[, x := 1], and a new key from data.table::setkey().

  • a hash of the values and the attributes of each column of each data.frame, and of each data.frame in a list of data.frames. The attributes of such a list, such as its names, have a hash too. This finds a change of values in place. Examples are data$d[1, x := 0], data$d[g == "a", y := NA] and data.table::set() on some rows. It also finds data.table::setorder(), and data.table::setattr() on a column or on the table. The error names the data and each changed column.

The hash leaves out the index that a data.table subset such as data$d[g == "a"] adds to the table, because the index changes no value.

Each other data element, for example a vector or a model, gets one hash of its whole value. The error then names the data and says "in its value". That hash leaves out each function in the value and the contents of each environment in it, such as that of a formula. R changes a function when it compiles it, so a read could look like a change. pbn does not check a data element that is a function or an environment, also an R6 object. Copy the data first with data.table::copy() when the analysis changes it, or make the change in a data step.

pbn hashes each data object before its first analysis in an R session, and after each analysis. An analysis that changes the data fails and stops the run, so the first hash holds for each later analysis. The time grows with the size of the data. On one computer, the hash after an analysis took 0.07 s for a data.table with one million rows and 20 columns of mixed types. It took 0.03 s for ten million rows and 5 numeric columns. The same data as a plain data.frame took 0.10 s and 0.23 s. The first analysis of each data object costs a second hash.

While run_plan() runs, an analysis also fails when it changes an object of the functions folder, for example CFG. plnr runs many analyses in one R session, so the change would reach each later analysis of that session. A result would then depend on the analyses that ran before it there. pbn checks each object that the functions folder made or changed when initialize_project() sourced it, other than a function, a plnr plan and .Random.seed. It compares the bytes of serialize() of each object before and after the analysis. That finds a new value, a new element and a new attribute. It compares them before and after each data function or data step too. A data function that changes such an object fails each analysis that gets its data. The error names the first top-level element that changed, for example CFG$table. It also says how: a new attribute such as the index of a data.table, a new or a gone element, or another value. The output function of make_outputs() and each expect_ function of save_results() get the same check in this R session.

While run_plan() runs, two more parts of the state of an R session cannot pass from one analysis to the next:

  • An analysis fails when it leaves a new object in the global environment, for example with ⁠<<-⁠ or assign(). .Random.seed does not count.

  • pbn takes the kind of random number generator of the run from RNGkind() at the start of run_plan(). It sets that kind again before each seed of a data function and of an analysis. An analysis that calls RNGkind() then changes no draw of a later analysis.

A data.table subset with a logical, for example CFG$table[group == "a"], adds an index to the table in place. Copy the table first with data.table::copy(), or set options(datatable.auto.index = FALSE) in the project. pbn sets neither.

The check has these limits:

  • It does not see a function inside an object, because R compiles a function after some calls.

  • It does not see the contents of an environment inside an object, for example that of a formula. It does not call an active binding.

  • It does not see a change of an object that already was in the global environment, other than an object of the functions folder.

  • The analysis that made the change fails, and the change stays in that R session. The run stops at that failure, see run_plan().

  • Without initialize_project(), pbn checks no object.

The check costs time in proportion to the size of the objects. One computer took about 45 microseconds for each analysis with a CFG of 49 elements. These held 5 data.tables of 100 rows, 20 KB in serialize().

For each scenario and simulation, pbn also adds one analysis named ⁠<scenario>__sim_<kkkk>__pbn_n_rows⁠. It counts the rows of each data element. save_results() stores the counts in manifest$n_rows_data, and leaves the analysis out of the results.

add_analyses() stops before it adds anything when an analysis of that name is in the plan already.

Value

Invisibly, the names of the analyses of the kind, in the order of the plan.

See Also

vignette("pbn"), which builds and runs a small fake project.

Other plan: add_data(), cohort_data(), get_data(), progress(), run_plan()

Examples

CFG <- list(
  scenarios = data.frame(scenario = c("real", "null"), sims = c(1, 2)),
  outcomes = c("y1", "y2")
)
p <- plnr::Plan$new()
pbn::add_data(p, "d", fn = function(scenario, sim) {
  return(data.frame(y1 = stats::rnorm(5), y2 = stats::rnorm(5)))
})
pbn::add_analyses(
  p,
  pbn::scenarios(CFG),
  name = "means",
  fn = function(data, argset) {
    return(data.frame(mean = mean(data$d[[argset$outcome]])))
  },
  outcome = CFG$outcomes
)
pbn::get_argset(p, "null", 2, "means", 2)

Add data to a plan

Description

add_data() adds the data name to the plnr plan p, as the steps raw, clean, cohort and after_cohort, or as one data function fn. plnr calls it once for each scenario and simulation, and gives the data to each analysis of that scenario and simulation.

Usage

add_data(
  p,
  name,
  fn = NULL,
  raw = NULL,
  clean = NULL,
  cohort = NULL,
  after_cohort = NULL,
  cache = FALSE
)

Arguments

p

A plan from plnr::Plan$new().

name

The name of the data. Each action function gets it as data[[name]].

fn

The free form: one data function, for data that does not fit the steps. Give fn or raw, not both.

raw

The first step, normally data_raw, a ⁠function(scenario, sim)⁠ that reads the real data or makes fake data.

clean

Optional. The step that gets the value of raw, normally data_clean, for example for names and types. It MUST return a data.frame with the same number of rows.

cohort

Optional. The step that gets the value of clean, or of raw without clean, normally data_cohort. It MUST return a cohort::CohortPipeline that starts with every row that it got.

after_cohort

Optional, and only with cohort. The step that gets the cohort::CohortPipeline, for example an imputation. It returns the data for the analyses, and pbn puts the exclusion table of the cohort on it. See the section A cohort as the data.

cache

TRUE saves the data on disk for each scenario and simulation. The next run reads it while the cache key is the same. See the section Cache.

Details

In the steps form, each rule for fn in this section and in the section Cache applies to raw.

plnr keys a data function on its arguments without a default. These are the key fields. Each key field of fn MUST be scenario, sim or a setting column of CFG$scenarios. Otherwise run_plan() stops before it runs anything. plnr calls fn once for each set of values of the key fields, and gives each analysis with those values the same data.

add_data() stops on these arguments of fn:

  • scenario or sim with a default. plnr does not key on it, so every scenario or simulation would get the same data.

  • sim without scenario. Every scenario would get the same data.

A data function without scenario and sim, for example one that reads a lookup table, runs once for the whole run and sets no seed.

pbn adds fn in a wrapper. The wrapper has the key fields of fn as its arguments, so plnr keys it in the same way. It calls fn with them by name, so another argument of fn with a default keeps its default. When sim is an argument, the wrapper calls set.seed(sim) before fn. The data of simulation k is thus the same in each run, and does not depend on the other scenarios of the run. A function that is called with no sim sets no seed.

The wrapper needs no object of the R session that adds it. run_plan() gives each worker the objects that the functions folder defines.

name MUST be one syntactic name that starts with a letter and holds only letters, digits, . and ⁠_⁠, for example "d". pbn names each step of the data ⁠<name>$<step>⁠ in the code that fake_md5 hashes. A $ in a name could thus match a step of another data. name MUST NOT be "hash", because plnr adds data$hash to the data of each analysis. Two data functions of one plan MUST NOT have the same name. Add data with add_data(), not with p$add_data(). save_results() reads the data functions of add_data() only.

While run_plan() runs, an error in fn or in a step fails each analysis that gets the data. When you call get_data() or p$get_data() by hand, the error stops the call.

Value

Invisibly, the name of the data.

The steps

pbn runs the steps in the order raw, clean, cohort and after_cohort, and gives the value of each step to the next one. Each step after raw MUST take exactly one argument without a default, or add_data() stops. pbn calls set.seed(sim) once, before raw. So ⁠raw = data_raw, clean = data_clean⁠ draws the same numbers as fn = function(scenario, sim) data_clean(data_raw(scenario, sim)).

pbn sees the value between the steps, so it checks the rule that the cleaning drops no row. Each exclusion goes through the cohort, which counts it. These values fail the data, as an error in fn does:

  • raw returns a data.frame, and clean returns a value that is not a data.frame, or a data.frame with another number of rows.

  • cohort returns a value that is not a cohort::CohortPipeline.

  • cohort gets a data.frame, and its pipeline starts with another number of rows, cp$n_total().

The error gives both numbers of rows. The checks compare the numbers of rows only, so the order of the rows and the columns MAY change. The checks compare the number of rows, not which rows: a step that drops one row and repeats another passes.

When raw returns a value that is not a data.frame, pbn does not check clean. An example is a list of two tables that clean joins. That list has no number of rows to compare, and it is a valid start. pbn does not check the rows of after_cohort.

Use fn for data that does not fit the steps, for example data that joins two cohorts. pbn then checks no rows inside fn.

An exclusion MAY apply to the rows of a reshape, for example one row for each person and time point. Add these rows as a second data element, with a second call of add_data(). Its raw builds the reshaped rows, and its cohort applies the exclusion, so the cohort counts it. Its raw MAY reshape the value of the raw of the first element. pbn sets the seed to sim before each data element, so both draw the same numbers.

A cohort as the data

fn or the step cohort MAY return a cohort::CohortPipeline after its exclusions. The analyses then get data[[name]] as the data.table of ⁠$get_included(<cohort>)⁠. ⁠<cohort>⁠ is the one cohort of the pipeline that no other cohort branches from. A pipeline with more than one such cohort fails the data. Each other value goes to the analyses as it is.

The step after_cohort reads the data of the cohort with cohort_data(), and returns its value. The value MAY be any R object other than NULL, for example a list of imputed data sets. pbn puts the exclusion table of the cohort and its number of rows at the start on the value, as keep_exclusions() does. These replace the attributes that the step set. So a call of keep_exclusions() in the step changes nothing, and a table from another cohort does not stay. The step MAY return the cohort::CohortPipeline that it got. Another cohort::CohortPipeline fails the data, because its exclusion table would replace that of the step cohort.

A step after the cohort in fn returns its value through keep_exclusions(), which puts the exclusion table on it.

pbn keeps the exclusion table of the cohort, and save_results() stores it in the element exclusions of the results. The table has one row for each exclusion step of the cohort and of the cohorts above it, in the order of the exclusion steps. It is a data.frame with these columns:

  • data, the name of the data.

  • step, the reason of ⁠$exclude_and_track()⁠.

  • n_before, n_excluded and n_after, the number of rows before the step, excluded by the step, and after the step. n_excluded and n_after are n_excluded and n_remaining of ⁠$consort()⁠.

The value carries the table in its attribute pbn_exclusions, and the number of rows given to the pipeline in its attribute pbn_n_before. save_results() writes that number to manifest$n_rows_before_exclusions. The attributes are how both come back from a worker: the R6 object stays on the worker.

Cache

With cache = TRUE, fn MUST have the arguments scenario and sim without a default. Call initialize_project() first. For each scenario and simulation, run_plan() writes the value to ⁠<home>/<version>_cache_gitexclude/<name>/<scenario>/sim_<kkkk>.qs2⁠. The value is the data.table and its exclusion table for a cohort. The cache key goes to ⁠sim_<kkkk>_key.qs2⁠ in the same folder. The cache key is the md5 of these parts:

  • the scenario, the simulation and the settings of the scenario.

  • for "real" only, the fingerprint of the data at the time of the use. It holds the name ⁠<folder name>/<path in the folder>⁠, the size and the modification time of each file under each folder of folders of initialize_project(). pbn reads no content of a data file. The path of a folder is not in the key. So the same files in another place give the same key when they keep their modification times. A copy with new times looks like changed data, so the data is computed again. A file that changed in place, and kept its size and its modification time, is not seen.

  • the md5 of each file of ⁠<version>_functions/⁠ whose name starts with data_, for example data_raw.R, data_clean.R, data_cohort.R and data_impute.R. initialize_project() computes them before it sources the files.

  • the code of fn, or of each step, deparsed without its source references.

  • the code of each function of ⁠<version>_functions/⁠ that fn or a step calls, also through other functions of the folder. pbn deparses each without its source references. A function counts when its name is in the code. That includes an argument such as lapply(x, f), a formula, and a string such as do.call("f", args). So a helper in utils.R counts. A function that only an analysis calls does not change the key.

  • CFG$data, when CFG has the element data.

  • each other element of CFG that fn, a step or a function of the part above reads as CFG$x or CFG[["x"]]. When that code uses CFG in any other way, for example CFG[[k]], cfg = CFG or f(CFG), each element of CFG counts. Otherwise, an element that only an analysis reads does not change the key.

  • the versions of R and pbn. The version of R covers the base packages.

  • the three parts of RNGkind().

The key file also records the version of each package that was loaded in the R session that computed the value, after fn returned. On a worker, that is the worker. The record leaves out the base packages. It also leaves out the packages that run the plan, tests and documents: pbn, plnr, foreach, doParallel, doFuture, future, future.apply, globals, listenv, parallelly, progressr, iterators, qs2, digest, uuid, progress, testthat, pkgload, devtools, callr, processx, ps, knitr, rmarkdown and evaluate. pbn loads qs2 before the record, so each record holds the packages that qs2 loads, such as Rcpp. A later use compares each recorded version with utils::packageVersion() now. A package with another version, or one that is not installed now, computes the value again.

Each use of the cache stops when a data_*.R file on disk differs from the file that initialize_project() hashed and sourced: changed, added or removed. The error names the file. Run initialize_project() again. A file with its recorded size and modification time is not hashed again, so a change that keeps both is not found.

The key holds no other part of ⁠<version>_functions/⁠. These changes leave the key the same, and the run reads the old data:

  • a function whose name the data code builds when it runs, for example get(paste0("f", 1)).

  • an object of the folder that is neither a function nor an element of CFG. Examples are a lookup vector in utils.R and a function inside a list.

When the key is the same, run_plan() reads the value from the cache and does not call fn or a step. Each analysis sets its own seed, so its results are the same as with a new value. Otherwise, or when a cache file cannot be read, it calls fn or the steps and writes the cache. To compute every value again, delete the folder ⁠<version>_cache_gitexclude/⁠. No argument does that.

For each scenario and simulation, run_plan() prints one line with cat(). The line says that the data came from the cache, with the date and time of the cache file. Or it says that pbn computed it, and why. The reason names each changed data_*.R file, CFG$data, each changed element of CFG that the data code reads, such as CFG$ncc, or the settings. It names changed raw data with its folders, for example "the raw data in the folder lookup". It names a changed fn as "the data function of add_data()", and each changed step as, for example, "the function given as clean". It names each changed function that the data calls, for example "the function lower_names". It can also name the kind of random number generator, or each package with another version. With workers = 1, the line comes before the data function runs. With more workers, run_plan() prints the lines after the run, in the order of the plan.

run_plan() writes each file to a temporary file in the same folder, and renames it. plnr runs the data of one scenario and simulation in one task, so two workers of one run never write the same file. When two runs write one file at the same time, the last rename wins, and each file is whole. The cache file holds its key too, so a cache file and a key file from two runs give a new computation.

The cache folder holds data for each person. When the project is a git repository, git MUST ignore it: run_plan() stops before it runs anything when git does not ignore the cache files. Add the line ⁠*gitexclude*⁠ to the .gitignore of the project.

p$get_data() and p$run_one() by hand use the cache too, and print the same line. pbn computes the key at the time of the call, with the same rules.

See Also

vignette("pbn"), which builds and runs a small fake project.

Other plan: add_analyses(), cohort_data(), get_data(), progress(), run_plan()

Examples

p <- plnr::Plan$new()
pbn::add_data(
  p,
  "d",
  raw = function(scenario, sim) return(data.frame(X = stats::rnorm(3))),
  clean = function(d) return(stats::setNames(d, tolower(names(d))))
)

Declare one block of the manuscript, with its formatter and its items

Description

block() declares one element of the list blocks in ⁠<version>_functions/blocks.R⁠. The function of the block returns numbers, and the formatter turns them into the text of the manuscript.

Usage

block(fn, format, items = character(0))

Arguments

fn

A function of results. It returns the raw value of the block: a data.frame or a data.table of numbers and labels.

format

The name of the formatter, one string. It is the name of a house formatter, or of a function in ⁠<version>_functions/formatters.R⁠.

items

The checklist items that the block answers, as a character vector of "<id>:<item>" strings, for example c("strobe:13a", "strobe:14a"). The default is no item.

Details

The rule set house_2026_11_26 and the newer sets need block() for each element of blocks:

blocks <- list(
  "Results para 1: effect" = pbn::block(
    function(results) results$effect,
    format = "effect",
    items = c("strobe:17")
  )
)

The raw value MUST hold numbers as numbers. A character or factor column holds labels only. No cell of such a column MAY match ⁠[0-9][.,][0-9]⁠, ⁠[0-9]%⁠, ⁠[0-9] \(⁠ or ⁠\b[nNpP] ?[=<>] ?[0-9]⁠. Each of these patterns is a formatted number, such as 0.80, ⁠68.7%⁠, ⁠3 (⁠ and n = 3. A comparison in a label, such as ⁠Education < 16 years⁠, passes. save_results(), update_blocks(), show_blocks(), show_block() and txt() stop on such a cell. The error names the block, the column and the first cell that matches. The check reads the value only, so a block MAY call any function, for example paste0() to make a name.

The formatted value of a block is formatter(value). A formatter is a function of one argument, the raw value. It returns a character vector with one string for each row, or a data.frame or a data.table. Its columns MAY be of mixed types. pbn has five house formatters. Each of them uses the minus sign U+2212 for a negative number:

name columns example
ci est, lo, hi; digits (default 2) ⁠0.80 (95% CI 0.46 to 1.16)⁠
p p p < 0.001, p = 0.047
effect est, lo, hi, p; unit, digits (default 2) ⁠(0.80 points, 95% CI 0.46 to 1.16, p < 0.001)⁠
n_pct n, total; digits (default 1) ⁠1,037 (68.7%)⁠
mean_sd mean, sd; digits (default 1) 30.7 (4.8)

p gives p < 0.001 below 0.001, and else 3 decimals. A row with NA in a column that the formatter needs gives NA.

A project formatter is a function in ⁠<version>_functions/formatters.R⁠. It wins over a house formatter of the same name. That file MUST hold only assignments of a name to ⁠function(...)⁠. A project formatter sees CFG and the functions of the functions folder, in show_block(), in txt() and in the file of to_one_file(). pbn leaves it out of manifest$source_md5 under the same conditions as blocks.R, see save_results(). So a change of a formatter keeps the results current. The rule blocks_list of check_project() fails a use of a name of formatters.R in a file other than blocks.R and formatters.R.

In blocks.R, format MUST be one string, and items MUST be a call c("<id>:<item>", ...) of strings, so that check_project() reads them without running code. An ⁠<id>⁠ holds lower-case letters, digits and -. An ⁠<item>⁠ holds no space and no :.

Value

An object of the class pbn_block: a list with fn, format and items.

See Also

show_block(), txt(), update_blocks().


Check the file of to_one_file() on this computer

Description

check_one_file() runs the file ⁠<version>_one_file.R⁠ of the project in a new R session, on copies of the folders of the project. It prints PASS when the real results are those of the project, or else the first difference.

Usage

check_one_file(...)

Arguments

...

Nothing. A call with an argument stops. check_one_file() takes the version and the paths of the server from the last initialize_project() of this R session.

Details

Run the project as normal first, so that ⁠<version>_results/real/⁠ holds its real results. In a one-file project, that folder is ⁠<version>_results/fake/⁠, see the section The folder fake/ of initialize_project(). The run of the file writes ⁠real/⁠ of its temporary project folder, as on the server. Write the file with to_one_file(), and call initialize_project() again in this R session, with one_file_home and one_file_folders.

check_one_file() then does these steps:

  1. It makes the lines of to_one_file() in memory, with the code of the project and the paths of the server of the last initialize_project(). It compares them with ⁠<version>_one_file.R⁠ in the project, line by line. This R session is the one source of the paths, so a change of one_file_home in the run script also makes the file older. Only the line of the header with the version of pbn and the date does not count. When a line differs, the file is older than the code of the project. It prints FAIL with the number of the first line that differs and the line in both files, each cut to 80 characters. It says to run to_one_file() again. A file of an older pbn, with the argument one_file, also gets this FAIL, and the text says so. It prints FAIL also when the project has no such file.

  2. Without real results, it stops here. So the file of a project MAY be checked for ASCII, for a parse and for a left-out function before the first full run.

  3. It compares manifest$source_md5 of the real results with the md5 of the files of the project now, without the files that the manifest leaves out, see source_md5 of save_results(). When they differ, the results of the project are older than its code. It prints FAIL with the changed files and says to run ⁠<version>_run.R⁠ again. It runs nothing.

  4. It reads manifest$failed_fake_checks of the real results. When it names a fake scenario with a failed assertion, it prints FAIL with the scenario and its check.csv, as read_results() does. It runs nothing.

  5. It makes a temporary folder with an empty project folder, and a copy of each folder of the project with all its files. The empty project folder stands for the server, where there is no functions folder and no pbn.yml.

  6. It writes a copy of the file of the project to the temporary folder. In the copy, each line with a path of the server gets the temporary path. These are the lines where to_one_file() with the temporary paths writes another line. It runs the copy with Rscript in a new R session. So the check runs the file that goes into git.

  7. It compares results.qs2 and results_gitexclude.qs2 of the real results of the run with those of the project, element by element.

  8. It calls each block of show_block() on the real results of the project and on those of the run, in one more new R session. That session attaches no package of the run script. It compares what show_block() prints for each page of each block, as text, without the line ⁠FAKE REAL DATA⁠. A block that stops on either results, or that prints other text, is a FAIL that names the block.

Five fields of the manifest MAY differ, and the comparison leaves them out:

  • run_date, the date of the run.

  • packages, the loaded packages, because the new R session loads other packages than the R session of the normal run.

  • the column from_cache of data_cache, because the copy has no cache.

  • fake_real_data, because the file never runs on fake real data. See initialize_project().

  • failed_fake_checks, because the file runs no fake scenario. Step 4 checks it on the real results of the project.

The comparison also leaves ⁠<version>_functions/blocks.R⁠ and ⁠<version>_functions/formatters.R⁠ out of source_md5, also for results of an older pbn that hold them. Every other element MUST be the same, also source_md5, data_files and cache_key. Two doubles are the same when they differ by at most 1e-6 of the larger absolute value, or by at most sqrt(.Machine$double.eps), about 1.5e-8, the tolerance of all.equal(), which counts near zero. The same model in two R sessions MAY differ in the last digits, and an iterative fit such as lme4::lmer() MAY differ in the eighth digit, because it stops at its own convergence tolerance. No printed number shows it. Every other value MUST be identical, also a double with a class, such as a Date or a POSIXct. The attributes MUST be identical too, in any order. So the results do not depend on the place of the project and of its folders. The copies keep the modification times of the files, with file.copy(copy.date = TRUE). That is why data_files and the cache key agree. pbn reads no content of a data file, so a copy with new times looks like changed data. The times are whole seconds, so a copy that loses a part of a second, as on Windows, still agrees.

When the run of the file stops with an error, check_one_file() prints FAIL with the exit status and the last 20 lines of the output of the run, and compares nothing. On PASS, it deletes the temporary folder. On FAIL, it keeps it, and the text names the folder with the file and the output of its run.

The check copies each folder, so it needs the disk space of the real data once more. These are its limits:

  • It cannot check what differs on the server, for example the versions of R and of the packages there.

  • It runs the file with Rscript, and on the server a person pastes it into an interactive R session. So it does not cover code that depends on interactive().

  • It compares the blocks on the real data of this computer. A block that stops only on other data, for example on an empty table, passes here.

  • pbn reads no content of a data file. A data file that changed in place and kept its size and its modification time is not seen.

Value

Invisibly, TRUE on PASS and FALSE on FAIL.

See Also

vignette("pbn"), section "Running on an air-gapped server".

Other one file: export_blocks(), show_blocks(), to_one_file()


Check a project against the house layout

Description

check_project() checks a project folder against the rules of its file pbn.yml and prints one line per finding. In a non-interactive R session it quits with status 1 when any rule fails.

Usage

check_project(path = ".")

Arguments

path

The project folder. It MUST hold the file pbn.yml.

Details

The first line names the rule set of pbn.yml, and counts its changes and its allowed paths. A rule with no finding prints one PASS line, and a rule that is off prints one OFF line. Each finding prints one line: ⁠PASS|WARN|FAIL <rule> <detail>⁠. The detail of a WARN or a FAIL ends with ⁠Fix:⁠ and the change that removes the finding. A count line comes last.

Every rule reads one list of files and their folders:

  • When path is the top folder of a git repository, the list is the output of ⁠git ls-files --cached --others --exclude-standard⁠. These are the tracked files, and the untracked files that git does not ignore.

  • Otherwise, the list is every file and folder on disk.

Both lists leave out .DS_Store, .Rhistory, .RData, the Word lock files ⁠~$*⁠, and everything in ⁠.git/⁠ or ⁠.Rproj.user/⁠.

A version older than the newest is frozen and cannot change. So these rules read only the files of the newest version, the vNN with the largest NN: run_script_initialises, results_contract, results_current, built_outputs_current, built_layout, real_folder_from_server, scenario_checks, comment_share, no_local_copy_of_pbn_function, loc_per_file, cyclomatic_complexity, no_environment_variables, no_cross_version_reads, no_escape_hatches, no_local_assign, no_absolute_paths, no_plot_title, no_plot_subtitle, no_plot_caption, blocks_list and real_results_are_fake. The rules that read each .R file still read an .R file outside the version items, such as adhoc/x.R. In ⁠vNN_results/⁠, unknown_path reads only the folder of the newest version. frozen_versions_unchanged checks the older versions.

The rules, with their level in the set house_2026_12_02, are below. The set house_2026_12_01 has the same rules at the same levels, without pbn_yml_committed, draft_manuscript_names, built_layout and real_folder_from_server. Its readme_and_changelog and display_numbering do not read what this set adds to them, and its guidelines_valid fails the key reported_in. The set house_2026_11_28 also does not have agents_points_to_rules and built_outputs_current. The set house_2026_11_27 also does not have results_current, and its guidelines_valid fails the key not_applicable. The set house_2026_11_26 also does not have display_numbering. The set house_2026_11_25 also does not have built_reads_source, manual_has_supplement, manual_si_has_main, guidelines_valid and guidelines_covered. The set house_2026_11_20 also does not have no_plot_title, no_plot_subtitle and no_plot_caption. The set house_2026_11_19 also does not have built_reads_own_version, built_has_run and manual_not_ahead. The set house_2026_11_17 also does not have frozen_versions_unchanged, readme_and_changelog, changelog_with_code, comment_share, no_cross_version_reads and no_escape_hatches. A rule that the set of the project does not have prints no line.

  • lower_case_names (FAIL): a file or folder name has a capital letter. Everything under ⁠background/⁠ is not checked. These are exempt: README.md, CHANGELOG.md, AGENTS.md, CLAUDE.md, LICENSE, DESCRIPTION, a top-level dotfile, a top-level ⁠*.Rproj⁠ file, file extensions, and the initials in ⁠manuscript/manual/vNN_<INITIALS>.docx⁠ and ⁠manuscript/manual/vNN_<INITIALS>_<suffix>.docx⁠, and in the drafts of an agent with the same names in ⁠manuscript/draft/⁠.

  • run_script_initialises (FAIL): a vNN_run.R at the top level has no call pbn::initialize_project() whose version argument is the string "vNN". A call with an argument that initialize_project() does not have does not count, and the detail names that argument.

  • version_items_complete (FAIL): a vNN_run.R has no ⁠vNN_functions/⁠, or the reverse.

  • frozen_versions_unchanged (FAIL): one of these is true:

    • a version older than the newest has no vNN_frozen.md5 of freeze_version(). A version is a vNN_run.R or a ⁠vNN_functions/⁠ at the top level, and the newest is the one with the largest NN. So a deleted vNN_frozen.md5 of an older version fails. The newest version needs none. The fix names the call pbn::freeze_version("vNN").

    • a file of a version changed, came or went after freeze_version() wrote its vNN_frozen.md5. The files are vNN_run.R and each file under ⁠vNN_functions/⁠, as freeze_version() lists them from the disk. The detail names the file, with changed, added or removed. A .R file whose line ends change between LF and CR LF, and nothing else, does not count as changed. A change of the line ends of any other file counts, see freeze_version().

    • a line of vNN_frozen.md5 is not ⁠<md5> <path>⁠.

  • readme_and_changelog (FAIL): README.md or CHANGELOG.md is not at the top level, or CHANGELOG.md has no section for a version. A section is a line that starts with ⁠## vNN⁠, with a space or nothing after it, for example ⁠## v01⁠ or ⁠## v01 (2026-11-19)⁠. A version is a vNN_run.R or a ⁠vNN_functions/⁠ at the top level. From the set house_2026_11_20, a version is also the vNN of a file ⁠manuscript/manual/vNN_<INITIALS>.docx⁠ with a name that manual_manuscript_names passes. README.md says what the project is, how to run it and why its code is as it is. CHANGELOG.md says what changed in each version. The detail is README.md: missing, CHANGELOG.md: missing or ⁠CHANGELOG.md: no section "## vNN"⁠. From the set house_2026_12_02, the section ⁠## vNN⁠ also names each file ⁠manuscript/manual/vNN_<INITIALS>.docx⁠ and ⁠manuscript/manual/vNN_<INITIALS>_<suffix>.docx⁠ of its version, as text anywhere in the section. A section ends at the next line that starts with ⁠# ⁠ or ⁠## ⁠. The detail is then ⁠CHANGELOG.md: the section "## vNN" does not name <file>⁠.

  • agents_points_to_rules (FAIL): AGENTS.md is not at the top level, or it does not hold the sentence ⁠Before you write code, run `Rscript -e 'pbn::rules()'`.⁠. A line break or a run of spaces counts as one space. rules() prints the rules of the project.

  • changelog_with_code (WARN): in a git repository, a vNN_run.R or a file under ⁠vNN_functions/⁠ differs from the last commit, and CHANGELOG.md does not. A change is staged or not staged, or the file is untracked and git does not ignore it. A deleted file counts too. In a repository without a commit, each staged file is a change. The rule reads the project folder path only, also when it is a folder inside a repository. When git is not installed or path is not in a git repository, the rule has nothing to compare. It then prints one PASS line that says so. The detail is ⁠<file>: changed since the last commit, and CHANGELOG.md did not change⁠.

  • pbn_yml_committed (WARN): in a git repository, ⁠git status --porcelain -- pbn.yml⁠ prints a line. So pbn.yml differs from the last commit, or git does not track it. A person decides a change to pbn.yml, and the commit records the decision. When git is not installed or path is not in a git repository, the rule prints one PASS line that says so.

  • results_contract (FAIL): a ⁠vNN_results/<scenario>/results.qs2⁠ or a ⁠vNN_results/<scenario>/sim_NNNN/results.qs2⁠ of pbn 2026.11.22 fails check_results(), or a results.qs2 is directly in ⁠vNN_results/⁠.

    The rule also reads each ⁠vNN_results/<scenario>/sims_gitexclude/sim_NNNN.qs2⁠ on the disk, also when git ignores it, and fails a file that fails check_results(). A clone of the repository has none, and the rule then needs none.

    The rule also reads each results_gitexclude.qs2 beside a results.qs2, and each sim_NNNN_gitexclude.qs2 beside a sim_NNNN.qs2, also when git ignores it. It fails when the file does not hold exactly the analysis kinds that the manifest of the results file puts there. check_results() does not check it.

  • results_current (FAIL): a ⁠vNN_results/<scenario>/results.qs2⁠ of the newest version comes from other code than the files on the disk now. The rule finds the files on the disk, also when git ignores them. The rule compares manifest$source_md5 with the md5 of vNN_run.R and of each file of ⁠vNN_functions/⁠ now. The two lists, sorted by file name, MUST be identical, so a file name twice in the manifest fails. The files that cannot change the results do not count, such as blocks.R. The detail names the scenario and the first file that differs, in the C locale. The rule reads only the manifest of results.qs2, and never results_gitexclude.qs2. A file that results_contract fails for its shape gives no FAIL here.

  • gitexclude_not_tracked (FAIL): git tracks a path with gitexclude in its name, from ⁠git ls-files⁠ in path. Such a path holds data for each person. When git is not installed or path is not in a git repository, the rule has nothing to check. It then prints one PASS line that says so.

  • scenario_checks (FAIL): a ⁠vNN_results/<scenario>/check.csv⁠ has a value of pass that is not TRUE, holds no assertion, or has no column pass that R can read. save_results() writes these files.

  • manual_manuscript_names (FAIL): a file in ⁠manuscript/manual/⁠ does not match ⁠^v[0-9]{2}_[A-Z]{2,4}[0-9]?(_[a-z0-9]+)?\.docx$⁠. The suffix is one word of lower-case letters and digits, for a second file of the same version, such as the supporting information v02_AB_si.docx.

  • draft_manuscript_names (FAIL): a .docx file at any depth under ⁠manuscript/draft/⁠ has a name that does not match the pattern of manual_manuscript_names. An agent saves its Word drafts there. Each other file passes, such as the .qmd, .md and ⁠_setup.R⁠ of a manuscript on fake numbers, which built_reads_source sends there.

  • manuscript_reads_real (FAIL): an .R, .qmd or .Rmd file in ⁠manuscript/built/⁠ calls read_results() or pbn::read_results() with a scenario argument that is not the string "real". A call without scenario passes. In .qmd and .Rmd files, the rule reads the R chunks that knitr::purl() extracts and the inline R code.

  • built_reads_own_version (FAIL): an .R, .qmd or .Rmd file in ⁠manuscript/built/vNN/⁠ calls read_results() or pbn::read_results() with a version argument that is not the string "vNN". A variable and a call without version fail too. The rule reads the code as manuscript_reads_real does, and it fails a file that R cannot parse. It does not read a file in ⁠manuscript/built/⁠ outside a folder ⁠vNN/⁠, or a file of another language, such as .py. The detail lists each call that fails. From the set house_2026_11_26, the rule also reads each txt() call and each read_blocks() call.

  • built_reads_source (FAIL): a file in ⁠manuscript/built/vNN/⁠ does not read the numbers of its source. A version is one-file when its vNN_run.R gives one_file_home in a top-level call pbn::initialize_project(). pbn parses the run script and runs nothing. In a one-file version, a file fails without a read_blocks() or txt() call, and on a read_results() call. Each file there also fails while vNN_results/real/blocks.qs2 does not exist, or has the attribute pbn_fake of import_blocks(), because the numbers are then fake. In another version, a file fails on a read_blocks() call. The rule reads the code as manuscript_reads_real does. It does not read a file outside a folder ⁠vNN/⁠.

  • built_has_run (FAIL): a folder ⁠manuscript/built/vNN/⁠ has no vNN_run.R at the top level. In a git repository, an empty folder is not in the list of files, so the rule does not see it. The detail is ⁠manuscript/built/vNN: there is no vNN_run.R⁠.

  • built_outputs_current (FAIL): the newest run version vNN does not keep a current copy of ⁠vNN_results/real/output/⁠ in ⁠manuscript/built/vNN/⁠. vNN_run.R fails without a call pbn::copy_outputs("vNN"), without a call of pbn::make_outputs(), and when each such call comes before the first call of pbn::make_outputs(). The rule parses the script and runs nothing. Each file of the output folder fails without a copy of the same name and md5 in the built folder. A missing built folder holds no copy. A file of the built folder fails when it has an output name of display_numbering and the output folder does not have it, also when there is no output folder. The rule reads the disk, also when git ignores the files. copy_outputs() writes the copies. In each set, the rules that read a manuscript or an .R file skip such a file at the top of ⁠manuscript/built/vNN/⁠.

  • built_layout (FAIL): the top of ⁠manuscript/built/vNN/⁠ of the newest run version holds a file or a folder other than these:

    • a .docx file but reference.docx,

    • a file with an output name of display_numbering, as copy_outputs() writes it,

    • the folder ⁠resources/⁠.

    Each other file, such as a .qmd, an .md, ⁠_setup.R⁠, references.bib or reference.docx, belongs in ⁠manuscript/built/vNN/resources/⁠. render_built() renders the .qmd files there and moves the .docx files to the top. The list of files leaves out the Word lock files ⁠~$*⁠, so the rule ignores them. Word deletes such a file when it closes the document. Without a run script or without the folder, the rule has no finding.

  • manual_not_ahead (FAIL): a file ⁠manuscript/manual/vNN_<INITIALS>.docx⁠ has NN at or above MM, the largest version of a vMM_run.R. The run scripts and the manuscripts share one version counter. So a hand edit of version vMM is ⁠v(MM+1)_<INITIALS>.docx⁠, and the next run version is v(MM+2). The detail is ⁠manual vNN is ahead of the newest run vMM: freeze vMM and start vPP with pbn::new_version("vMM", to = "vPP")⁠, with PP = NN + 1. The rule does not read a name that manual_manuscript_names fails. Without a vNN_run.R, the rule has nothing to compare. It then prints one PASS line that says so.

  • manual_has_supplement (FAIL): a main file ⁠manuscript/manual/vNN_<INITIALS>.docx⁠ has no supplement ⁠manuscript/manual/vMM_<INITIALS>_si.docx⁠ with MM at or below NN. The initials of the supplement MAY differ. The supplement suffix is exactly si, so a file with another suffix is neither a main file nor a supplement. The rule reads ⁠manuscript/manual/⁠ only, so a draft in ⁠manuscript/draft/⁠ does not count. A project without a supplement turns the rule off with rules: manual_has_supplement: off in pbn.yml.

  • manual_si_has_main (FAIL): a supplement ⁠manuscript/manual/vNN_<INITIALS>_si.docx⁠ has no main file ⁠manuscript/manual/vNN_<INITIALS>.docx⁠ with the same version and the same initials. The detail names the main file to add.

  • fake_data_names (FAIL): a file in a folder ⁠output_fake_data/⁠ has a name without the prefix fake_data_, or a file with the prefix is in another folder. make_outputs() writes these folders.

  • no_local_copy_of_pbn_function (FAIL): a top-level assignment in a ⁠vNN_functions/*.R⁠ file defines a function with the name of a pbn export. The one exception is get_data: a project MAY name its data function get_data(scenario, sim), and a run script calls the export as pbn::get_data(). The set house_2026_11_17 does not know the exports create_project, freeze_version, new_version and verify, so a local function with such a name passes there.

  • loc_per_file (FAIL): an .R file has more than limit code lines, as counted by org::loc_per_file(). The house limit is 1000. The rule reads each .R file of the project but vNN_one_file.R.

  • cyclomatic_complexity (FAIL): a function scores above limit in cyclocomp::cyclocomp(). The house limit is 15, the limit of the lint gate of the house packages. The rule reads the .R files of loc_per_file. It scores each function that a top-level assignment defines, and each function in a list() of a top-level assignment, as ⁠<list>$<name>⁠. A function inside a function counts toward the outer function. Top-level code that is not a function gets no score. The rule parses each file and runs no code of it. It skips a file that R cannot parse, which loc_per_file fails. The detail gives the file, the function and its score. A path under allow allows each function of one file.

  • comment_share (WARN): in vNN_run.R or an .R file at the top of ⁠vNN_functions/⁠, the share of comment lines is more than limit. The share is the comment lines divided by the lines that are not blank. The house limit is 0.25, so a file of 20 such lines MAY have 5 comment lines. The parse data decides what is a comment, so a ⁠#⁠ in a string does not count. A line with code and a comment after it is a comment line. A section marker is not a comment line. A section marker is a comment with text and then four or more = or - at its end, as in ⁠# PART 1 ====⁠. The rule skips a file that R cannot parse. The detail is ⁠<file>: <n> of <m> lines that are not blank are comments, <share>, above the limit of <limit>⁠. An explanation of why the code is as it is goes into README.md, and what changed goes into CHANGELOG.md.

  • no_environment_variables (FAIL): a run script or a file in a functions folder uses Sys.getenv or Sys.setenv.

  • no_cross_version_reads (FAIL): a string constant of vNN_run.R or of an .R file at the top of ⁠vNN_functions/⁠ names another version or the folder ⁠adhoc/⁠. The rule splits each string at / and ⁠\⁠. A string fails when one of its parts is one of these:

    • vMM, with MM other than NN, as in read_results("v01") in v02_run.R.

    • vMM_ and an item of the layout: run.R, functions, results, cache_gitexclude, test, check_functions.R, one_file.R or frozen.md5. An example is "../v01_functions/get_data.R".

    • adhoc, as in "adhoc/helpers.R".

    These pass:

    • the version of the file and its items, and a comment.

    • a column name such as "v01_age", and "v1" and "v100".

    • a part with more words, such as "an adhoc analysis of v01".

    • a string that paste0() or sprintf() builds. The rule misses it.

    A column or a level with the name v01 fails, so allow its file in pbn.yml. The rule skips a file that R cannot parse, and a string of more than 1000 bytes. The detail is ⁠<file>:<line>: "<the string, cut at 40 characters>" names vMM⁠, or ⁠names adhoc/⁠.

  • no_local_assign (FAIL): an .R file uses a construct of forbid at any depth. The house forbid holds all seven constructs: local(), assign(), delayedAssign(), assignInNamespace(), assignInMyNamespace(), ⁠<<-⁠ and ⁠->>⁠. Each of these creates or changes an object in a place other than the line where it stands. The rule reads the .R files of loc_per_file, parses each file and runs no code of it. A call with the prefix of its own package, ⁠base::⁠ or ⁠utils::⁠, counts. A call of the same name from another package passes. A variable or an argument named local or assign passes, and so do ⁠<-⁠, ⁠->⁠, = and ⁠:=⁠. The rule skips a file that R cannot parse. The detail gives the file, the line and the construct. A path under allow allows each finding of one file.

  • no_escape_hatches (WARN): vNN_run.R or an .R file at the top of ⁠vNN_functions/⁠ calls suppressWarnings(), suppressMessages(), try(), tryCatch() or withCallingHandlers(), at any depth. Each of these can hide a warning or an error of the run. A call with the prefix ⁠base::⁠ counts. A call of the same name from another package passes. So do a word in a comment or a string, and a variable or an argument named try. The rule skips a file that R cannot parse. The detail gives the file, the line and the call. A path under allow allows each finding of one file. Give the reason in a comment in pbn.yml.

  • no_absolute_paths (FAIL): a string constant of an .R file of loc_per_file is an absolute path, or a path starts from a string constant. The rule reads the strings from the parse data, so a comment does not count. The arguments of a call pbn::initialize_project() are exempt, because a project declares its paths there, also one_file_home and one_file_folders. A string is an absolute path when it starts with one of these:

    • /, a name of letters, digits, ., ⁠_⁠ or - that starts with a letter or ⁠_⁠, and / again, as in "/home/a/x.csv" or "/data/".

    • ⁠~/⁠ or ⁠~\⁠, the home folder.

    • a drive letter, : and / or ⁠\⁠, as in "C:/x", "C:\\x" or "N:/durable/x".

    • ⁠\\⁠ and a letter or a digit, the start of a UNC path such as "\\\\server\\share".

    These strings pass:

    • "/" and "~".

    • the regular expressions "^/", "/$" and "/.*$".

    • a URL such as "https://a.org/b".

    • the formats "%s/%s" and "%Y/%m/%d", and the fraction "1/2".

    • the formula "y ~ x", and "/month".

    • the relative paths "data/x.csv", "./x" and "../x". A path with .. leaves the project folder, and it passes too.

    • a path with one name and no second /, such as "/data", and a string of more than 1000 bytes. The rule misses these.

    The rule also fails a call of file.path(), base::file.path() or fs::path() whose first argument is a string constant, for example file.path("data", "x.csv") or file.path("/", "data"). A path that starts from a constant is absolute, or it depends on the working directory. A path to data starts from pbn::folder(). A path for output starts from the folder that pbn gives the function, such as dir of make_outputs(). A call whose first argument is a name or a call passes, for example file.path(dir, "fig2.png") or file.path(tempdir(), "x"). A path that paste0() or sprintf() builds stays outside the rule.

    The detail is ⁠<file>:<line>: "<the string, cut at 40 characters>"⁠, or ⁠<file>:<line>: file.path("<the first argument, cut at 40 characters>", ...)⁠. A path under allow allows each finding of one file.

  • no_plot_title (FAIL): an .R file of loc_per_file gives a figure a title. A figure has no title, no subtitle and no caption, because its legend belongs in the manuscript. The rule fails each of these:

    • a call ggtitle() with a value of its first argument label.

    • an argument title of labs().

    • an argument title of plot_annotation(), by name or as its first argument.

    • an assignment to ⁠<x>$labels$title⁠.

    A call MAY have the prefix ⁠ggplot2::⁠ for ggtitle() and labs(), and ⁠patchwork::⁠ for plot_annotation(). A call of the same name from another package passes. R matches the arguments of a call as it does in a run: by name, by a part of a name and by position. These pass:

    • the value NULL, as in labs(title = NULL), which removes the title.

    • the other arguments, as in labs(x = "Age", colour = "Group", tag = "A") and plot_annotation(tag_levels = "A").

    • a theme element, as in theme(plot.title = element_text()).

    • an argument title or caption of another function, as in knitr::kable(d, caption = "x").

    • a call that R cannot match, as one with an argument that the function does not have, and a title that do.call() or a ... passes. The rule misses these.

    The rule parses each file and runs no code of it. It skips a file that R cannot parse. The detail is ⁠<file>:<line>: <call>(<argument> = ...)⁠, for example v01_functions/output.R:12: ggplot2::labs(title = ...), or ⁠<file>:<line>: <target> <- ...⁠. A path under allow allows each finding of one file.

  • no_plot_subtitle (FAIL): as no_plot_title, for a subtitle: the argument subtitle of ggtitle(), by name or as its second argument, the argument subtitle of labs() and of plot_annotation(), and an assignment to ⁠<x>$labels$subtitle⁠.

  • no_plot_caption (FAIL): as no_plot_title, for a caption: the argument caption of labs() and of plot_annotation(), and an assignment to ⁠<x>$labels$caption⁠.

  • blocks_list (FAIL): for each functions folder, one of these is true:

    • a file other than vNN_functions/blocks.R assigns blocks at its top level. pbn leaves blocks.R out of manifest$source_md5, so the blocks MUST be in that file.

    • more than one top-level assignment of blocks.R assigns it.

    • its value is not a call of list(), or the list is empty.

    • an element has no name, or a name comes twice.

    • an element is not a function, or the name of a function that a top-level assignment of the functions folder defines.

    • a top-level expression of blocks.R is not an assignment with ⁠<-⁠ or = of a name to ⁠function(...)⁠, or of blocks to list(...). Examples are library(x), options(...), set.seed(1), an if and fmt <- sprintf. Such code runs when pbn sources the folder, so it can change the results.

    • a name that blocks.R assigns at its top level, and another file of the folder assigns too. The detail names both places.

    • another file of the folder, or vNN_run.R, uses a name that blocks.R assigns at its top level. Examples are a helper fmt(), and CFG after CFG$labels <- ... in blocks.R. The run would then depend on a file outside source_md5. A name after $ or @ and the name of an argument do not count.

    The detail is ⁠<file>:<line>: <what>⁠. A folder without blocks and without blocks.R passes. initialize_project() makes the same checks of blocks.R, and puts it back into manifest$source_md5 when one fails, also when this rule is warn or off.

    From the set house_2026_11_26, the rule also fails each of these:

    • an element of blocks that is not a call pbn::block(fn, format, items).

    • a format that is not one string, or that names no house formatter and no function of formatters.R.

    • an items that is not a literal c("<id>:<item>", ...) of strings.

    • a top-level expression of vNN_functions/formatters.R that does not assign a name to ⁠function(...)⁠.

    • a name of formatters.R that a file other than blocks.R uses or assigns.

    The rule does not run the blocks, so it does not see their raw values. save_results(), update_blocks(), show_blocks(), show_block() and txt() check each raw value as block() says.

  • real_results_are_fake (WARN): a file vNN_results/real/results.qs2 holds manifest$fake_real_data TRUE. Its run had fake_real_data = TRUE of initialize_project(), so its numbers are not those of the real data. It passes when no such file is in the list of files. In a git repository, a real results file that git ignores is not in the list, so the rule does not see it.

  • real_folder_from_server (FAIL): the newest run version is a one-file version, and its ⁠vNN_results/real/⁠ holds a file or a folder other than export_blocks.txt and blocks.qs2. built_reads_source says what a one-file version is. A person saves the pages of export_blocks() on the server as export_blocks.txt, and import_blocks() writes blocks.qs2 from them. No other function of pbn writes ⁠real/⁠ in a one-file project on this computer: the run writes the scenario "real" to ⁠vNN_results/fake/⁠. The rule reads the disk, also when git ignores the files. It leaves out the files of an OS or an editor of the list of files.

  • guidelines_valid (FAIL): a file ⁠guidelines/<x>.yml⁠ breaks the checklist schema below. Each such file gives one FAIL, and its detail names its first 3 problems and counts the rest. The rule reads each .yml file directly in ⁠guidelines/⁠. It does not read a file in a folder under ⁠guidelines/⁠, or a file with another extension, such as .yaml.

  • guidelines_covered (WARN): a result item of a valid file ⁠guidelines/<x>.yml⁠ has no block, or a block names an item that no valid file has. Each such item and each such tag gives one WARN. The rule reads the literal items of each block() in the blocks.R of the newest functions folder, without running code. A tag of a file that fails guidelines_valid gives no WARN. make_checklists() then checks the manuscript text against the formatted strings of the blocks. From the set house_2026_11_28, a result item with the key not_applicable needs no block. A block that names such an item gives one WARN: it is tagged but marked not applicable.

  • display_numbering (FAIL): the numbered figures and tables of the outputs, of the manuscript and of its citations do not agree. The rule reads the output folders ⁠vNN_results/<scenario>/output/⁠ and ⁠vNN_results/<scenario>/output_fake_data/⁠ of the newest run version. It reads each name there without the prefix fake_data_. Each name MUST be one of these:

    • ⁠fig_N_<name>⁠, ⁠fig_sN_<name>⁠ or ⁠fig_edN_<name>⁠, a figure, with any extension. N is a whole number from 1. s marks a supplementary figure, and ed marks an Extended Data figure.

    • tables.xlsx, with one sheet tab_N, tab_sN or tab_edN for each numbered table.

    • data_behind_figures.xlsx, with the plotted data in sheets ⁠fig_N_<name>⁠, ⁠fig_sN_<name>⁠ or ⁠fig_edN_<name>⁠. A figure MAY have more than one sheet.

    • ⁠fig_N_<name>_external.txt⁠ or ⁠tab_N_<name>_external.txt⁠, an item that the output function does not make, such as a flow chart. sN or edN MAY replace N.

    • ⁠nonum_<name>⁠, anything else.

    A sheet ⁠nonum_<name>⁠ passes in both workbooks. A file ⁠tab_N_<name>⁠ that does not end with ⁠_external.txt⁠ fails, because tables go in tables.xlsx. Each figure file other than an ⁠_external.txt⁠ item MUST have a sheet of its number in data_behind_figures.xlsx of its folder. Each sheet fig_N_ MUST have a figure file of its number there.

    The manuscript is the newest version NN of ⁠manuscript/manual/vNN_<INITIALS>.docx⁠, then its ⁠_si⁠ files, and the files ⁠manuscript/built/vNN/*.md⁠. From the set house_2026_12_02, it is also each file ⁠manuscript/built/vNN/resources/<stem>.md⁠ with a file ⁠resources/<stem>.qmd⁠, but checklist_*.md. The other .md files of ⁠resources/⁠ are notes, such as DISPLAY.md, and their citations do not count. Without a manuscript, the rule checks the names only. A citation is "Figure 1", "Fig. 1", "Table 1", "Figure S1" or "Supplementary Figure 1", which is Figure S1. "Extended Data Fig. 4", "Extended Data Figure 4" and "Extended Data Table 1" cite the Extended Data series, also in the plural. A range such as "Tables 1-3" cites each number of it. A list needs the plural word, and it follows the Oxford comma. It has two items, as in "Figures 1 and 2", or three or more that end in ", and", as in "Figures 1, 2, and 3". A range MAY be an item. A list such as "Figures 1, 2 and 3" fails, and its items still count as citations. A comma after one item ends the citation, so "Figures 1 and 2, 25 and 30 persons" cites Figures 1 and 2 only. The text of a tracked deletion and of the old place of moved text in a .docx file does not count. There are six series: the figures, the tables, the supplementary figures, the supplementary tables, the Extended Data figures and the Extended Data tables. In each series, the first citations MUST come in the order 1, 2, 3, with no gap. A paragraph that starts with "Figure 2." or "Table S1:" is a caption. So is "Figure 2." in Markdown emphasis, and "fig.png", the text of an image. An Extended Data caption also accepts "Fig." and the delimiter "|", as in "Extended Data Fig. 4 | The gap". The text MUST cite each captioned item outside its own caption.

    The numbered items of the outputs are the figure files, the sheets tab_ of tables.xlsx and the ⁠_external.txt⁠ items of ⁠vNN_results/real/output/⁠. Without that folder, they are the items of the first ⁠output_fake_data/⁠ folder of the version in name order, such as ⁠fake/output_fake_data/⁠ of a one-file project. Each numbered item MUST be cited or captioned in the manuscript. Each item of the manuscript MUST be a numbered item of the outputs. The PASS line names the folder.

  • unknown_path (WARN): the house layout does not name a top-level file or folder. The layout names vNN_run.R, ⁠vNN_functions/⁠, ⁠vNN_results/⁠, ⁠vNN_cache_gitexclude/⁠, ⁠vNN_test/⁠, vNN_check_functions.R, vNN_one_file.R, check_project.R and pbn.yml, among others. From the set house_2026_11_19, it also names vNN_frozen.md5 of freeze_version(). From the set house_2026_11_26, it also names the folder ⁠guidelines/⁠. A top-level dotfile and a top-level ⁠*.Rproj⁠ file are never unknown. The rule also reads the files directly in ⁠vNN_results/⁠. There it names the run log run.md, its PDF run.pdf and its errors file run_errors_gitexclude.md, and no rule needs them. It reads no deeper, so it never warns on the folders ⁠output/⁠ and ⁠output_fake_data/⁠ that make_outputs() writes in ⁠vNN_results/<scenario>/⁠, or on the folder ⁠sims_gitexclude/⁠ that save_results() writes there.

A checklist file ⁠guidelines/<x>.yml⁠ holds one reporting guideline, in the checklist schema of the methods repository. Copy the file from there. guidelines_valid fails the file unless each of these is true:

  • The file is valid YAML, and a map.

  • It has no key other than id, title, version, source, citation, designs, design and items.

  • id and title are each one string. id has only the characters a-z, 0-9 and -, and no other file has the same id.

  • version, source and citation MAY be missing. Each one that is there is one string.

  • A key that is there has a value. ⁠version:⁠ with nothing after it, or ⁠citation: ~⁠, fails. This holds for designs and design too, and for the designs of an entry.

  • designs MAY be missing. When it is there, it is a YAML sequence of strings, such as ⁠[cohort]⁠. One string, such as designs: cohort, or a map fails. The same holds for the designs of an entry.

  • design MAY be missing. When it is there, it is one of designs.

  • items is a YAML sequence with at least one entry. A map fails.

  • Each entry has no key other than item, section, topic, kind, designs and text. Its item, section, topic, kind and text are each one string. Quote an item id such as "2", because YAML reads 2 as a number.

  • The kind of each entry is result, prose or author.

  • The designs of an entry MAY be missing, and the entry then belongs to each design of the file. When it is there, the file has designs, and each value is one of them.

  • An item id comes once per design, among the entries that design keeps. STROBE has three entries with the item id 15, one for each design, so it passes.

A project copy MAY add the key design, such as design: cohort. pbn then keeps the entries whose designs include it, and the entries without designs.

From the set house_2026_11_28, an entry of a project copy MAY have the key not_applicable: "<reason>". The reason tells why the item does not apply to the project. Its value MUST be one string that is not empty, and guidelines_valid fails any other value. The checklist schema of the methods repository does not have this key. make_checklists() gives the item the status ⁠not applicable: <reason>⁠.

From the set house_2026_12_02, a prose or an author entry of a project copy MAY have the key reported_in: "<location>". The location is where the manuscript answers the item, such as "Methods, Statistical analysis; Figure S1". Its value MUST be one string that is not empty. guidelines_valid fails any other value. It also fails the key on a result entry, whose location comes from its blocks, and on an entry with not_applicable. make_checklists() writes the location in the column Reported in, with the status reported.

The R parser, not a regular expression, finds the calls, the assignments and the symbols.

vNN_one_file.R at the top level is the file of to_one_file(). It holds the paths of a server by design, and pbn writes it. So loc_per_file, cyclomatic_complexity, no_local_assign, no_absolute_paths, no_plot_title, no_plot_subtitle and no_plot_caption do not read it, and no rule takes it for a run script. Put it in git: it is what ran on the server.

Value

Invisibly, a data.frame of the findings with the columns rule, status, path and detail.

The file pbn.yml

Each project MUST have the file pbn.yml in its top folder path. pbn reads no other file. A file pbn.yaml stops check_project() with the advice to rename it. The smallest pbn.yml is one line:

extends: house_2026_11_25

The key extends names a house rule set. A set is a dated file in the folder ⁠rules/⁠ of pbn, and pbn never changes a set after its release. A change to the house rules is a new set with a new date. pbn never chooses a set for a project. So a new version of pbn does not change the rules of a project. To read the set, run readLines(system.file("rules", "house_2026_11_25.yml", package = "pbn")).

The set gives each rule one of three levels:

  • fail: a finding is FAIL, and check_project.R ends with status 1.

  • warn: a finding is WARN.

  • off: the rule does not run, and its one line is OFF.

The parameters of the rules are limit of loc_per_file, limit of cyclomatic_complexity, limit of comment_share and forbid of no_local_assign. The list of the rules above gives their house values.

The key rules MAY change the level of a rule, a parameter, or both. A change merges into the entry of the set. So cyclomatic_complexity: {limit: 25} keeps the level fail. The short form lower_case_names: warn changes the level only. forbid MAY list fewer constructs than the house set.

The key allow MAY list paths for each rule, relative to path. A path allows the findings with that path and the findings of each path under it. So the folder adhoc allows adhoc/Notes.txt and adhoc/Old/Data.csv, but not adhoc2/x.R. A final / changes nothing: adhoc and ⁠adhoc/⁠ are the same entry. pbn does not look on the disk for a file or a folder of that name. An allowed finding is WARN, with (allowed) before its fix. A path that matches no finding is a WARN of the rule allow.

Three rules are locked: results_contract, gitexclude_not_tracked and fake_data_names. The first two keep data for each person out of git. The third keeps the output of fake data apart from the output of real data. pbn.yml cannot set a locked rule to warn or off, and cannot allow a path for it. It cannot name a rule of check_results() either.

The key ignore MAY list folders at the top level, such as ⁠archive/⁠, that no rule reads: their files give no finding, not even a WARN. Use it for old work that nothing runs. A final / changes nothing. An entry MUST be one folder at the top level that the house layout of the set does not name, so it cannot be ⁠manuscript/⁠, ⁠background/⁠, ⁠adhoc/⁠ or a folder of a version. From the set house_2026_11_26, it cannot be ⁠guidelines/⁠ either. A folder that does not exist is no error. The locked rules still read an ignored folder, so a tracked file with gitexclude in its name fails there too. The first line of the report counts the ignored folders.

This pbn.yml changes two rules, allows three paths and ignores one folder:

extends: house_2026_11_25
rules:
  cyclomatic_complexity: {limit: 25}
  unknown_path: off
allow:
  lower_case_names: [adhoc/Old_notes.txt, adhoc/Drafts/]
  no_local_assign:
    - adhoc/explore.R
ignore: [archive/]

check_project() and initialize_project() stop before any rule runs on each of these, with a message that names the key:

  • there is no pbn.yml. The message gives the one line to write.

  • there is a file pbn.yaml, or a file pbn_allow.txt. For pbn_allow.txt, the message gives its lines as the YAML of the key allow.

  • pbn.yml is not valid YAML. This includes a key that is there twice and a tab. The message holds the message of the yaml package.

  • there is no key extends, or it names a set that pbn does not have.

  • a key other than extends, rules, allow and ignore.

  • a name that is not a rule. The message names the nearest rule.

  • a rule that the set of extends does not have. The message names the oldest set with it.

  • a parameter that the rule does not have.

  • a level other than fail, warn and off.

  • a limit that is not a whole number of 1 or more. For comment_share, a limit that is not a number from 0 to 1.

  • a construct in forbid that the rule does not know, or an empty forbid. To turn the rule off, set its level to off.

  • a value under allow that is not a path, for example off. YAML reads off, yes and no as booleans, so a path with such a name needs quotes.

  • a change or an allowed path of a locked rule.

  • an entry of ignore that is not one folder at the top level, is a name of the house layout, is there twice, or is a file.

See Also

Other checks: freeze_version(), verify()

Examples

home <- file.path(tempdir(), "pbn_check_example")
dir.create(file.path(home, "v01_functions"), recursive = TRUE)
writeLines("extends: house_2026_11_25", file.path(home, "pbn.yml"))
writeLines(
  'pbn::initialize_project(version = "v01", home = ".", folders = c(main = "x"))',
  file.path(home, "v01_run.R")
)
writeLines("# A fake project", file.path(home, "README.md"))
writeLines(c("# Changelog", "", "## v01"), file.path(home, "CHANGELOG.md"))
pbn::check_project(home)

unlink(home, recursive = TRUE)

Check a results object against the contract

Description

check_results() checks a results object against the contract of save_results(). It reports each rule as PASS or FAIL, and it stops on nothing.

Usage

check_results(x)

Arguments

x

The results object, normally from read_results().

Details

The rule element_names checks that the manifest is there. The rules manifest_scenario, manifest_data and manifest_source check that it is valid. The seven rules:

  • element_names: x is a list with the element manifest exactly once and at least one other element. The other element MAY be missing when manifest$analyses puts a kind in results_gitexclude.qs2. Each element has a name. Each name is syntactic, so make.names() does not change it, and no name is there twice.

  • exclusions_table: when x has an element exclusions, it is a data.frame with the columns step, n_before, n_excluded and n_after, and MAY have the column data. save_results() writes data for the exclusion table of a cohort. When manifest$stacked is TRUE, it also has the column sim that save_results() adds when it stacks. On every row, n_before - n_excluded == n_after. Without an element exclusions, the rule passes and says so.

  • allowed_objects: each element at each depth is one of these:

    • a data.frame, of any class that inherits from data.frame. This includes a data.table and a tibble.

    • an atomic vector of any length and of any class, including a matrix, an array, a factor, a Date and a POSIXct.

    • NULL.

    • a list of such elements, named or not. The list has no class, or only classes from this set: list, AsIs, table, noquote, difftime, Date, POSIXct, factor and integer64.

    Each other element fails, and the detail names its path, its class and a fix. This includes a function, an environment, an S4 object, an R6 object, a formula and each other list with a class. A fitted model of the class lm, glm, gam, merMod, brmsfit, coxph or lavaan fails too. The detail has a fix for a model, a formula, an htest, a POSIXlt, a package_version and an sf geometry. For each other object, convert it to a data.frame or a plain list.

    The walk goes into the columns of a data.frame, so a model in a list column fails too. It also goes into the attributes of each object, and it writes the path of an attribute as attr(x$a, "terms"). So the terms attribute of a model frame fails. The walk skips the attributes that R and data.table set: names, dim, dimnames, row.names, class, levels, tzone, units, comment, sorted, index and .internal.selfref.

  • no_row_per_person: no element at any depth of the results has one value for each row of the data. manifest$n_rows_data holds one row count, or one for each data element. For a cohort, manifest$n_rows_before_exclusions and manifest$n_rows_after_exclusions hold the rows before and after the exclusions too. manifest$n_rows_lists holds the rows of each data.frame of a data element that is a list of data.frames with 2 or more numbers of rows. For each count n of 2 or more in any of the four, the rule fails each of these:

    • a data.frame with n rows.

    • an atomic vector of length n, also a factor, a Date or a POSIXct.

    • a matrix or an array with a dimension n.

    The walk goes into lists, the columns and list columns of data.frames, and attributes. It does not go into manifest or exclusions. A count that is NA, 0 or 1 checks nothing, and a manifest$n_rows_data without another count checks nothing too. A table with fewer rows than the data passes, and so does a vector with one value for each group.

    For stacked results, the rule is about the rows of one simulation. It takes the results apart into the value of each simulation. It uses the column sim of each data.frame and the entries ⁠sim_<kkkk>⁠ of each other value. It checks each simulation against its own counts in manifest$n_rows_by_sim. So 400 simulations of a 1-row table, a stacked table of 400 rows, pass with 400 rows of data in each simulation. A table with one row for each person in one simulation fails. Stacked results without manifest$n_rows_by_sim get the rule of unstacked results. An older pbn wrote their counts as NA, so they check nothing.

  • manifest_scenario: manifest has the elements scenario, sim and sims, and scenario is one string.

  • manifest_data: manifest has exactly one of data_files and fake_md5. It has data_files when scenario is "real", and fake_md5 when scenario is another string. fake_md5 MUST be one string of 32 lower-case hex digits. data_files MUST be a data.frame with the columns file, size and mtime. Each file is a name that comes once, each size a number of 0 or more, and each mtime a number. It has 0 rows when the data folders have no file. A manifest with data_md5, the md5 of the data files of an older pbn, fails this rule: run the scenario again. For "real", manifest$fake_real_data MUST be TRUE or FALSE. A real manifest of an older pbn has no fake_real_data, so it fails this rule: run the scenario again.

    For "real", manifest$failed_fake_checks MUST be a character vector without attributes, also no names. It MAY be empty. Each element MUST match ⁠^[a-z0-9_]+$⁠, MUST NOT be NA or "real", and MUST come once. The element MUST be there when manifest$pbn_version is a version of 2026.11.25 or newer. A manifest without it and without such a version passes, as the results of an older pbn do.

  • manifest_source: manifest$source_md5 is a named character vector of md5 values, each a string of 32 lower-case hex digits. It names the run script ⁠<version>_run.R⁠ of manifest$version, or a vNN_run.R when the manifest has no valid version. A results file that pbn 2026.11.20 or older wrote has no source_md5, so it fails this rule.

check_results() checks the object of results.qs2 or of ⁠sim_<kkkk>.qs2⁠. The object of a file of gitexclude MAY hold data for each person, and these rules do not apply to it. See the section Two files of save_results().

Value

A data.frame with one row per rule and the columns rule, status and detail. status is "PASS" or "FAIL".

See Also

Other results: read_results(), render_run(), save_results()

Examples

x <- list(
  manifest = list(
    scenario = "real",
    sim = 1L,
    sims = 1L,
    data_files = data.frame(file = "main/d.csv", size = 120, mtime = 1.8e9),
    fake_real_data = FALSE,
    source_md5 = c(v01_run.R = "fedcba9876543210fedcba9876543210"),
    n_rows_data = 100L
  ),
  exclusions = data.frame(
    step = "age 18 or more",
    n_before = 100,
    n_excluded = 4,
    n_after = 97
  ),
  estimates = data.frame(term = "x", estimate = 1.2),
  p_interaction = 0.04
)
pbn::check_results(x)

Work on the data of a cohort and keep its exclusion table

Description

cohort_data() gives the data of a cohort::CohortPipeline after its exclusions. keep_exclusions() puts the exclusion table of the pipeline on the value of a step after the cohort, such as an imputation.

Usage

cohort_data(cp)

keep_exclusions(x, cp)

Arguments

cp

A cohort::CohortPipeline after its exclusions.

x

The value of the step after the cohort, any R object other than NULL. For example a data.table, a list of imputed data sets or a mids object.

Details

A step after the cohort reads the data with cohort_data(). As the step after_cohort of add_data(), it returns its value, and pbn puts the exclusion table on it:

data_impute <- function(cp) {
  d <- pbn::cohort_data(cp)
  lapply(1:5, function(k) impute_once(d))
}

At the end of a data function fn, the step returns pbn::keep_exclusions(imp, cp), so that the table stays.

cohort_data() returns ⁠cp$get_included(<cohort>)⁠. ⁠<cohort>⁠ is the one cohort of the pipeline that no other cohort branches from, the cohort that add_data() gives the analyses. It stops on a pipeline with more than one such cohort.

keep_exclusions() returns x with two attributes. pbn_exclusions holds the exclusion table of cp, and pbn_n_before holds cp$n_total(), the number of rows given to the pipeline. The analyses get x, and save_results() writes the table to the element exclusions. The section A cohort as the data of add_data() gives the columns.

For a value that is not a data.frame, the check of run_plan() for an analysis that changes the shared data in place checks nothing. manifest$n_rows_data is the number of rows of one data set when x is a list of data.frames with one number of rows, and NA otherwise.

A function that calls these two runs on each worker of run_plan(), so each worker needs pbn installed.

Value

cohort_data(): a data.table. keep_exclusions(): x with the attributes pbn_exclusions and pbn_n_before.

See Also

vignette("pbn"), which imputes after the cohort.

Other plan: add_analyses(), add_data(), get_data(), progress(), run_plan()

Examples

d <- data.table::data.table(id = 1:6, age = c(15, 30, 41, 17, 52, 60))
cp <- cohort::CohortPipeline$new(d)
cp$exclude_and_track("root", "age under 18", "age < 18")
adults <- pbn::cohort_data(cp)
imp <- list(adults, adults)
attr(pbn::keep_exclusions(imp, cp), "pbn_exclusions")

Copy the real output of a version into its built manuscript folder

Description

copy_outputs() copies each file of ⁠<version>_results/real/output/⁠ into ⁠manuscript/built/<version>/⁠, so the built manuscript is next to its figures and tables. It also deletes each file there with an output name that is not in the output folder now, so a removed figure does not stay.

Usage

copy_outputs(version, home = ".")

Arguments

version

The version, such as "v01".

home

The top folder of the project. The default "." is the working directory.

Details

Call it in ⁠<version>_run.R⁠ after make_outputs(). A manuscript in ⁠manuscript/built/<version>/⁠ then reads a figure such as fig_1_gap.png from its own folder. The rule built_outputs_current of check_project() fails a run script without the call, and a copy that is missing, different or stale.

An output name is a name that the rule display_numbering allows in an output folder: ⁠fig_N_<name>⁠, ⁠fig_sN_<name>⁠, ⁠fig_edN_<name>⁠, tables.xlsx, data_behind_figures.xlsx, ⁠<key>_<name>_external.txt⁠ and ⁠nonum_<name>⁠. copy_outputs() deletes no file with another name, such as manuscript.qmd. A file with an output name in ⁠manuscript/built/<version>/⁠ belongs to copy_outputs(): do not put one there by hand.

Value

The paths of the copies in ⁠manuscript/built/<version>/⁠, invisibly. It creates that folder when it is missing. It stops when the output folder is missing or holds no file.

See Also

Other output: make_outputs(), panel_numbers(), plot_dag(), plot_path_model(), render_built(), stamp_fake()

Examples

home <- tempfile()
dir.create(file.path(home, "v01_results", "real", "output"), recursive = TRUE)
writeLines("x", file.path(home, "v01_results", "real", "output", "nonum_n.txt"))
copy_outputs("v01", home = home)
list.files(file.path(home, "manuscript", "built", "v01"))
unlink(home, recursive = TRUE)

Create a new project

Description

create_project() writes the files of a new project at version v01 into the folder home. The project passes check_project() at once, and verify() gives a PASS on the fake scenarios without the real data.

Usage

create_project(home = ".", folders = c(main = "../data"))

Arguments

home

The project folder. It MUST exist.

folders

The folders outside the project that the project reads, as for initialize_project(). The run script gets them as they are given.

Details

create_project() writes these files:

  • pbn.yml, with the line extends: house_2026_12_02.

  • v01_run.R, the run script. Its data steps are raw, clean and cohort, and it has one analysis kind, risk_difference. After make_outputs(), it ends without the real data, and otherwise calls copy_outputs().

  • ⁠v01_functions/⁠, with ⁠_cfg.R⁠, the data steps data_raw.R, data_clean.R and data_cohort.R, the analysis fit_risk_difference.R, the checks expect_known.R and the output function output.R.

  • README.md, with a title from the name of home, a section How to run, and the arithmetic of the fake scenario.

  • CHANGELOG.md, with the section ⁠## v01⁠.

  • AGENTS.md, a copy of system.file("templates", "AGENTS.md", package = "pbn").

  • .gitignore, with the line ⁠*gitexclude*⁠.

  • check_project.R, with the line pbn::check_project().

CFG$scenarios has the scenario real and the fake scenario known. known has 10 rows. The step cohort excludes 1, and the difference of the risks is 0.35. expect_known() checks both numbers.

The run script calls pbn::scenarios(CFG, only = setdiff(CFG$scenarios$scenario, "real")). So a run includes each fake scenario of CFG$scenarios, and never real. That is why verify("v01") gives a PASS on a computer without the real data. Its verdict line then says that the PASS covers the fake scenarios only. data_raw() stops for real with the message to replace the stop() with code that reads the real data. When that code is there, remove only from the call.

The files hold no comments. README.md says why, and CHANGELOG.md says what changed.

create_project() writes no file that is already there. It stops before it writes anything in each of these cases:

  • one of its files exists. The error names each such file.

  • the package cohort is not installed, because the step cohort needs it. The error gives the line that installs it: pak::pak(c("raubreywhite/pbn", "raubreywhite/cohort")).

When a write stops part way, create_project() removes each file and folder that the call created. So a second call can start again.

Value

Invisibly, the paths of the files that it wrote, relative to home.

See Also

Other project setup: end_unless_real(), folder(), initialize_project(), new_version(), real_data_is_fake(), rules(), scenarios()

Examples

home <- file.path(tempdir(), "pbn_create_example")
dir.create(home)
pbn::create_project(home = home)
pbn::check_project(home)

unlink(home, recursive = TRUE)

End the run script here unless the real data ran

Description

end_unless_real() ends a run script after save_results() when the scenario "real" is not among the scenarios of the run. The part of the script after it is for the real results only, for example the figures.

Usage

end_unless_real(scenarios)

Arguments

scenarios

The scenarios of the run, from scenarios().

Details

  • When "real" is in scenarios, end_unless_real() does nothing, and the script continues.

  • Otherwise, in a non-interactive R session, for example under Rscript, it prints one line, flushes the output and quits R with status 0. No line after it runs.

  • Otherwise, in an interactive R session, it stops with an error of class pbn_end_unless_real. The R session stays open.

Value

Invisibly, NULL, when "real" is in scenarios.

See Also

vignette("pbn"), which builds and runs a small fake project.

Other project setup: create_project(), folder(), initialize_project(), new_version(), real_data_is_fake(), rules(), scenarios()

Examples

CFG <- list(scenarios = data.frame(scenario = c("real", "null"), sims = 1))
pbn::end_unless_real(pbn::scenarios(CFG))

Check that a control analysis shows its bias

Description

expect_biased() checks that the estimate of a control analysis is biased over the simulations of a fake scenario. Use it for an analysis that MUST be wrong, for example a crude model in a scenario with a confounder.

Usage

expect_biased(x, truth, estimate = "estimate", by = NULL, label = NULL)

Arguments

x

The stacked results of one analysis kind, for example results$models. It is a data.frame with the column sim that save_results() adds. It has one row for each simulation, or for each simulation and group of by.

truth

The true value of the estimate. One number for every group, or a data.frame with the columns of by and a column truth, with one row for each group.

estimate

The name of the column of x that holds the estimate.

by

NULL, or the names of the columns of x that split it into groups, for example "term". Each group gets its own assertions.

label

NULL, or one string that starts the text of each assertion. NULL uses the expression of x, for example "results$models". Give a label when x is not a named object, or for two calls on one object.

Details

A control analysis shows that the fake scenario can find the error it was built for. When a crude model is not biased, the confounder of the scenario is too weak, and the recovery of the adjusted model shows nothing.

For each group, n is the number of simulations with a finite estimate. The bias is mean(estimate) - truth, and its Monte Carlo SE is sd(estimate) / sqrt(n). The assertion passes when ⁠|bias| > z * MCSE⁠, with the z of expect_recovers(), 3.89. Otherwise it fails, and the row says that the control did not show the bias it was built to show. The row shows the "can detect" value of expect_recovers(): the smallest bias that the assertion finds with a probability of 80%.

Below 100 simulations, the assertion fails with "too few simulations to check". It also fails when more than 5% of the simulations have a missing or infinite estimate, and when all estimates are equal.

Value

A data.frame with the columns assertion, expected, observed and pass, and one row for each group.

See Also

vignette("pbn"), which checks a crude model in a scenario with a confounder.

Other checks of fake scenarios: expect_recovers()

Examples

set.seed(1)
x <- data.frame(sim = 1:300, estimate = rnorm(300, 0.9, 0.2))
pbn::expect_biased(x, truth = 0.5)

Check that an analysis recovers the truth of a fake scenario

Description

expect_recovers() checks the bias, the standard error and the coverage of an estimate over the simulations of a fake scenario. It returns the assertions in the format of an ⁠expect_<scenario>()⁠ function.

Usage

expect_recovers(
  x,
  truth,
  estimate = "estimate",
  se = "se",
  lower = "lower",
  upper = "upper",
  by = NULL,
  level = 0.95,
  coverage = TRUE,
  label = NULL
)

Arguments

x

The stacked results of one analysis kind, for example results$models. It is a data.frame with the column sim that save_results() adds. It has one row for each simulation, or for each simulation and group of by.

truth

The true value of the estimate. One number for every group, or a data.frame with the columns of by and a column truth, with one row for each group.

estimate, se, lower, upper

The names of the columns of x that hold the estimate, its standard error and the limits of its confidence interval.

by

NULL, or the names of the columns of x that split it into groups, for example "term". Each group gets its own assertions.

level

The level of the confidence interval of lower and upper.

coverage

TRUE checks the coverage of the interval. FALSE makes no coverage assertion and needs no lower and upper. See the section Without coverage.

label

NULL, or one string that starts the text of each assertion. NULL uses the expression of x, for example "results$models". Give a label when x is not a named object, or for two calls on one object.

Details

expect_recovers() needs a fake scenario with random data and at least 100 simulations. A fixed scenario, for example one with values that a person computed by hand, MUST keep exact assertions that you write by hand.

The text of each assertion holds the label, the group of by, the measure and the truth, for example "results$models: bias of estimate against 0.673". The checks work on the scale of the columns. Give a log odds ratio, its standard error and its limits on the log scale, with a truth on the log scale. Do not give odds ratios. On the scale of the odds ratio, the estimate is biased, and the standard error is that of the log.

For each group and assertion, n is the number of simulations with the values that the assertion needs. The bias needs a finite estimate, the standard error a finite estimate and se, and the coverage a finite lower and upper. The empirical SE is sd(estimate) over these n simulations. z is 3.89, the two-sided normal quantile of 0.0001. The three assertions are:

  1. Bias: mean(estimate) - truth. Its Monte Carlo SE is sd(estimate) / sqrt(n). The assertion passes when ⁠|bias| <= z * MCSE⁠.

  2. Standard error: the relative error ModSE / EmpSE - 1 of the model SE ModSE = sqrt(mean(se^2)) against the empirical SE EmpSE. Its Monte Carlo SE is (ModSE / EmpSE) * sqrt(var(se^2) / (4 * n * ModSE^4) + 1 / (2 * (n - 1))). The assertion passes when ⁠|ModSE / EmpSE - 1| <= z * MCSE⁠.

  3. Coverage: the share of simulations where ⁠lower <= truth <= upper⁠. The assertion passes when the share is within z * sqrt(level * (1 - level) / n) of level.

Morris, White and Crowther (2019), Table 6, define these three performance measures and give a Monte Carlo SE for each. The SE of the relative error is a delta-method approximation. It assumes that the estimate is normal, and that se is independent of the estimate. The SE of the coverage uses level, not the observed share. Under a correct analysis the true share is level, and the observed share is 1 in many small studies, which gives an SE of 0.

Each row shows the observed value, the limit and the number of simulations. It also shows "can detect": the smallest error that the assertion finds with a probability of 80% at this number of simulations. For the bias, this is (z + 0.84) * sd(estimate) / sqrt(n). For the standard error, it is the ratio ModSE / EmpSE below and above 1. For the coverage, it is the true coverage below level. A large "can detect" value means that the check passes almost anything.

Value

A data.frame with the columns assertion, expected, observed and pass, and three rows for each group, or two with coverage = FALSE. Give it to rbind() with the other assertions of the ⁠expect_<scenario>()⁠ function.

The fewest simulations

An assertion fails with "too few simulations to check" when n is below:

  • 100 for the bias and the standard error. The bias uses sd(estimate), so its false-alarm probability is that of a t distribution. At 100 simulations it is 0.00018. At 30 it is 0.00054.

  • for the coverage, the smallest n that puts both limits inside 0 and 1, and at least 100. The limits are ⁠level +/- z * sqrt(level * (1 - level) / n)⁠. This is 288 for the level 0.95, and 137 for 0.9.

An assertion also fails when more than 5% of the simulations of the group miss a value that it needs. Each row shows its own number of missing simulations, also when it passes. Simulations where the model failed are not missing at random, so a pass with missing simulations is weaker.

An assertion fails on a value that cannot be right, and its row gives the count:

  • the standard error, on an se of 0 or less.

  • the coverage, on a lower above its upper.

  • the bias and the standard error, when all estimates are equal. The Monte Carlo SE is then 0.

Without coverage

With coverage = FALSE, expect_recovers() checks the bias and the standard error only. It gives no row for the coverage, so the coverage is not checked, and x needs no columns lower and upper. Each assertion then needs 100 simulations. Use it for a simulation that is too slow for 288 simulations, the number that the coverage of a 95% interval needs. Use it also for an analysis without a confidence interval. The bias and the standard error are the same as with coverage = TRUE.

The false alarms

A false alarm is a failed assertion for a correct analysis. It stops the run, and the same seeds give it again in the next run. So z is large. For each assertion the probability is about 0.0001. For one call with g groups and 3 assertions in each group, it is about 1 - (1 - 0.0001)^(3 * g):

Groups Assertions False alarm of the call
1 3 0.0003
6 18 0.0018
20 60 0.0060

The real probabilities are a little larger, because the bias is a t statistic and the coverage is a binomial count. At 300 simulations, the bias has 0.00012 and the coverage at the level 0.95 has 0.00028. There is no option to change z.

References

Morris TP, White IR, Crowther MJ. Using simulation studies to evaluate statistical methods. Statistics in Medicine. 2019;38:2074-2102. doi:10.1002/sim.8086

See Also

expect_biased() for a control analysis, and vignette("pbn").

Other checks of fake scenarios: expect_biased()

Examples

set.seed(1)
x <- data.frame(sim = 1:300, estimate = rnorm(300, 0.5, 0.2), se = 0.2)
x$lower <- x$estimate - 1.96 * x$se
x$upper <- x$estimate + 1.96 * x$se
pbn::expect_recovers(x, truth = 0.5)

Take the blocks off a server as text, and read them back

Description

export_blocks() prints the raw value of each block as R code, in pages with a checksum. import_blocks() reads the captured pages into ⁠<version>_results/real/blocks.qs2⁠, and read_blocks() returns those values for a manuscript.

Usage

export_blocks(version = NULL)

import_blocks(version, home = ".")

read_blocks(version, home = ".")

Arguments

version

The version, for example "v01". For export_blocks(), the default NULL is the version of the last initialize_project() in this R session.

home

The project folder. The default "." is the working folder.

Details

export_blocks()

export_blocks() runs on the server, after the file of to_one_file(). It needs initialize_project() in this R session, and it reads the blocks and the real results as show_blocks() does. For each block, it keeps the raw value, the value that save_results() writes to blocks.qs2. It does not call the formatter of a block(). It turns a data.table into a data.frame, because R cannot read the pointer of a data.table back. It stops on a block that stops, and the error names the block.

The text of block k is the output of base R dput() for a list. The list holds one element: the raw value, with the name of the block. The control of dput() is c("keepNA", "keepInteger", "niceNames", "showAttributes", "digits17"). With "digits17", each number has 17 significant digits, so the number after the import is the same double.

Each page has at most 35 lines: a header line and at most 34 lines of text. The header line is ⁠pbn-blocks <version> run <run date> block <k>/<n> page <p>/<P> md5 <m>⁠. The run date is that of show_block(). ⁠<m>⁠ is the first 8 hex characters of tools::md5sum() of the text lines of the page. pbn takes them without trailing white space, joined by "\n", with no final newline. An empty line follows each page.

When the real results have fake_real_data TRUE in their manifest, each header line ends with the token fake. Examples are a run of a one-file project on this computer, see initialize_project(). The pages of real data have no token.

import_blocks()

Copy or type the pages from the screen of the server into ⁠<version>_results/real/export_blocks.txt⁠. import_blocks() reads that file. It removes the trailing white space of each line and each empty line, and it ignores the lines before the first header line. The lines after a header line, up to the next header line, are the text of that page.

import_blocks() stops and writes nothing when:

  • the file has no header line,

  • a header line names another version, or the pages name more than one run date or more than one count of blocks,

  • some header lines end with the token fake and some do not,

  • the md5 of the text of a page differs from its header, and the error names the block and the page,

  • a page is missing, and the error names the block and the page,

  • a page comes twice with other text. A page that comes twice with the same text counts once.

  • R cannot parse the text of a block, or the text is not a list of one named value.

It rebuilds each value with eval(parse(text = text), envir = baseenv()). So import only the pages that export_blocks() printed, because import_blocks() runs the file as R code. It writes the named list of the values to ⁠<version>_results/real/blocks.qs2⁠ and overwrites that file. It writes there in a one-file project too, where the scenario real of this computer is in ⁠fake/⁠, see initialize_project(). When the pages end with the token fake, the list has the attribute pbn_fake = TRUE.

read_blocks()

read_blocks() returns ⁠<version>_results/real/blocks.qs2⁠ when it exists. Else it returns the blocks.qs2 of the scenario real of this computer, and it gives a warning that the numbers are fake. In a one-file project that file is ⁠<version>_results/fake/blocks.qs2⁠. In a project that is not one-file it is real/blocks.qs2 itself, so read_blocks() stops. txt() and make_checklists() read the blocks in the same way. The rule built_reads_source of check_project() says which functions a manuscript in ⁠manuscript/built/⁠ MUST use.

The values are fake when they come from another file than real/blocks.qs2, or when real/blocks.qs2 has pbn_fake = TRUE. For fake values in a document that knitr renders, such as a .qmd or an .Rmd, read_blocks(), txt() and make_checklists() add a knitr document hook. The hook puts the line ⁠**FAKE DATA**⁠ once at the top of the output, after the YAML header. A document that reads only real values gets no such line.

Value

export_blocks(): invisibly, the printed lines. import_blocks(): invisibly, the path of the blocks.qs2 that it wrote. read_blocks(): a named list with the raw value of each block.

See Also

vignette("pbn"), section "Running on an air-gapped server".

Other one file: check_one_file(), show_blocks(), to_one_file()


The path of a folder of the project

Description

folder() gives the path of one folder of folders of initialize_project(). Project code reads each folder outside the project through it.

Usage

folder(name = "main", ...)

Arguments

name

The name of the folder in folders of initialize_project(). The default "main" is also the name of one folder given without a name.

...

Parts of a path inside the folder, each one string, for example pbn::folder("main", "sub", "d.csv"). folder() joins them to the folder with /. A part MUST NOT start with /, ⁠\\⁠ or a drive such as ⁠C:⁠. It MUST NOT hold .., so a path never leaves the folder.

Details

folder() stops before initialize_project(), and on a name that the project does not declare. The error names the declared folders. A folder that does not exist still has its path, so the code of a fake scenario runs on a computer without the real data.

run_plan() gives the folders to each worker, so folder() works in a data function and in an analysis on a worker too.

The path of a folder is never in a results file or in a cache key. The manifest names the files of a folder ⁠<folder name>/<path in the folder>⁠, so the same data in another place gives the same results.

Value

The path of the folder, or of the path inside it, one string. A folder that existed at initialize_project() has its normalised path with /, and another folder has the path as folders gave it. Neither has a final / or ⁠\⁠, but a root such as "N:/" keeps it.

See Also

vignette("pbn"), which builds and runs a small fake project.

Other project setup: create_project(), end_unless_real(), initialize_project(), new_version(), real_data_is_fake(), rules(), scenarios()

Examples

home <- file.path(tempdir(), "pbn_folder_example")
dir.create(file.path(home, "v01_functions"), recursive = TRUE)
writeLines("extends: house_2026_11_25", file.path(home, "pbn.yml"))
writeLines("CFG <- list()", file.path(home, "v01_functions", "_cfg.R"))
pbn::initialize_project(
  "v01",
  home,
  folders = c(main = file.path(home, "data"), lookup = file.path(home, "codes")),
  env = new.env()
)
pbn::folder("lookup")
pbn::folder("main", "sub", "d.csv")

unlink(home, recursive = TRUE)

Freeze a version of a project

Description

freeze_version() writes the file ⁠<version>_frozen.md5⁠ in home, with the md5 of ⁠<version>_run.R⁠ and of each file under ⁠<version>_functions/⁠. The rule frozen_versions_unchanged of check_project() then fails when one of these files changes, or when a file comes or goes.

Usage

freeze_version(version, home = ".")

Arguments

version

The version, "v" and two digits, for example "v01".

home

The project folder.

Details

The file has one line for each file, ⁠<md5> <path>⁠, in the format of the command md5sum. Each path is relative to home, and the lines are sorted by path in the C locale. The files under ⁠<version>_functions/⁠ are all files at any depth, hidden files too.

The md5 of a file with the extension .R or .r is the md5 of its text with LF line ends. Each CR LF counts as LF, because R parses the file the same either way. So a checkout with CR LF line ends, for example on Windows with the git setting core.autocrlf = true, gives the same md5 for such a file. The md5 of every other file is that of its bytes. When each .R file has LF line ends, ⁠md5sum -c v01_frozen.md5⁠, run in home, also checks the files.

Freeze a version when its results go into a manuscript or to a reader. A change after that goes into a new version. A second call of freeze_version() writes the file again, so it records every change since the first call as intended. It then prints the files whose md5 it changes.

Value

Invisibly, the path of the file, relative to home.

See Also

Other checks: check_project(), verify()

Examples

home <- file.path(tempdir(), "pbn_freeze_example")
dir.create(file.path(home, "v01_functions"), recursive = TRUE)
writeLines("x <- 1", file.path(home, "v01_run.R"))
writeLines("f <- function() return(1)", file.path(home, "v01_functions", "f.R"))
pbn::freeze_version("v01", home = home)
readLines(file.path(home, "v01_frozen.md5"))

unlink(home, recursive = TRUE)

Get the data or the argset of one analysis at the console

Description

get_data() returns the data that the analyses of one scenario and simulation of the plan p get as data. get_argset() returns the argset of one analysis, so you do not type the name of the analysis.

Usage

get_data(p, scenario = "real", sim = 1)

get_argset(p, scenario = "real", sim = 1, name, i = 1)

Arguments

p

A plan from plnr::Plan$new(), with data from add_data(). get_argset() also needs analyses from add_analyses().

scenario

The scenario. The default is "real".

sim

The simulation, a whole number from 1 to the number of simulations of the scenario.

name

The name of the analysis kind, for example "models".

i

The counter of the extra dimensions of the kind, see add_analyses(). A kind without extra dimensions has 1 only.

Details

get_data(p, "null", 3) calls p$get_data() for the analysis null__sim_0003__pbn_n_rows. add_analyses() adds this analysis for each scenario and simulation, and it gets the same data as each other analysis of that scenario and simulation. So get_data() takes the path of p$get_data(): the seed sim, the steps of add_data(), and the cache with its one line. The value is the named list of the data elements, with the element hash that plnr adds. pbn::get_data(p)$d is the data d of "real".

get_argset(p, "null", 3, "models", 2) is p$get_argset("null__sim_0003__models__2").

Call get_argset() after add_analyses(). Call get_data() after add_data(), before or after run_plan(). Before add_analyses(), get_data() takes the scenarios of the last call of scenarios() before add_data(). initialize_project() forgets them. It then calls each data function with the scenario, the simulation and the settings, in the same way as plnr. The value then has no element hash. So the line d <- pbn::get_data(p, "real")$d works directly after add_data() in a run script.

Both stop on a scenario or a simulation that the plan does not hold, and the error names the values that it holds. get_argset() also stops on a kind or a counter that the plan does not hold for that scenario. An example is a kind with control = TRUE for "real".

To step through an action function by hand, put these lines first in it:

if (plnr::is_run_directly()) {
  argset <- pbn::get_argset(p, "null", 3, "models")
  data <- pbn::get_data(p, "null", 3)
}

Value

get_data(): a named list with one element for each data element, and hash. get_argset(): the argset, a named list.

See Also

vignette("pbn"), which steps through one analysis by hand.

Other plan: add_analyses(), add_data(), cohort_data(), progress(), run_plan()

Examples

CFG <- list(scenarios = data.frame(scenario = c("real", "null"), sims = 2))
p <- plnr::Plan$new()
pbn::add_data(p, "d", fn = function(scenario, sim) {
  return(data.frame(x = stats::rnorm(3)))
})
pbn::add_analyses(
  p,
  pbn::scenarios(CFG),
  name = "means",
  fn = function(data, argset) return(data.frame(mean = mean(data$d$x))),
  outcome = c("y1", "y2")
)
pbn::get_data(p, "null", 2)$d
pbn::get_argset(p, "null", 2, "means", 2)$outcome

Start a project version

Description

initialize_project() sets the paths of a project version and sources its functions folder. It MUST be the first call in every vNN_run.R.

Usage

initialize_project(
  version,
  home,
  folders,
  env = .GlobalEnv,
  ...,
  fake_real_data = FALSE,
  one_file_home = NULL,
  one_file_folders = NULL,
  generated = NULL,
  packages_missing_ok = character()
)

Arguments

version

The version, written as "v" and two digits, for example "v01".

home

The project folder. It holds ⁠<version>_run.R⁠, ⁠<version>_functions/⁠ and the file of the rules pbn.yml.

folders

The folders outside the project that the project reads, as a named character vector, for example c(main = "../data", lookup = "../codes"). One folder MAY have no name, and it then gets the name main. Each name MUST be a syntactic R name, once. A folder MAY be absent, for example on a computer without the real data. Only save_results() for the scenario "real" then stops.

env

The environment that the functions folder is sourced into.

...

Nothing. A call with the removed argument data_raw stops, and the error says how to use folders. Each argument after ... MUST be given with its full name.

fake_real_data

TRUE when the folders of folders on this computer hold fake files in the formats of the real data, and FALSE, the default, otherwise. See the section Fake real data. A call with one_file_home MUST NOT give fake_real_data = TRUE, and it stops.

one_file_home

The project folder on the server without a network, one string, for example "N:/durable/project", or NULL, the default. to_one_file() writes it into its file. See the sections Paths of the server and The folder fake/.

one_file_folders

The folders of folders on the server, as a named character vector, or NULL, the default. It MUST name exactly the folders of folders. One folder MAY have no name on both sides, and it then gets the name main.

generated

NULL. The file of to_one_file() gives a value here. Do not write it by hand. See the section One file.

packages_missing_ok

The packages that MAY be missing on this computer, as a character vector, for example "qs". initialize_project() gives it to org::initialize_project(), whose check of the packages of the functions folder then leaves them out. The default character() leaves out no package. The file of to_one_file() never gives it, so the server needs each package.

Details

initialize_project() does these steps in this order:

  1. It reads the rules of check_project() from home/pbn.yml. It stops on each error of pbn.yml that stops check_project(), also when the file is missing. It stops when an .R file at the top of ⁠<version>_functions/⁠ is a FAIL of the rule loc_per_file. The limit, the level and the section allow of pbn.yml act as in check_project(). The error names each file with its count of code lines and the limit.

  2. It computes the md5 of ⁠<version>_run.R⁠ and of each file in ⁠<version>_functions/⁠, before it sources them. save_results() stores them in manifest$source_md5, without ⁠<version>_functions/blocks.R⁠. From the rule set house_2026_11_26, it also leaves out ⁠<version>_functions/formatters.R⁠, see source_md5 of save_results(). The section The md5 of the run script gives the text of the run script that the md5 leaves out.

  3. It lists each file under each folder of folders that exists, at any depth, with its size and its modification time. This is the fingerprint of the data. pbn never reads the content of a data file, so a file of 60 GB costs what a small file costs. save_results() stores the fingerprint in manifest$data_files of the scenario "real". A file that the run writes later is not in the list. The section The fingerprint of the data gives the rules.

  4. It calls org::initialize_project() with folders_to_be_sourced set to ⁠<version>_functions⁠ and max_loc_per_file = Inf, because step 1 checks the code lines, and with packages_missing_ok. pbn gives org no folder of folders, so org::project holds home, computer_id and env only. Before this step, it sets the value of real_data_is_fake(), so the functions folder can read it.

Project code finds a folder with folder(), for example file.path(pbn::folder("main"), "d.csv"). Call folder() inside a function: a top-level call in a file of the functions folder runs before initialize_project() sets the folders, and it stops.

initialize_project() drops a final / or ⁠\⁠ of home and of each path of folders, one_file_home and one_file_folders. So "N:/durable/project/" is "N:/durable/project", and a path that pbn builds from it never holds ⁠//⁠. A root keeps its separator: "N:/" and "/" stay as they are.

The results folder is ⁠<home>/<version>_results⁠. save_results() creates it. initialize_project() creates no folder, also no folder with today's date. It stops when ⁠<version>_functions/⁠ does not exist.

initialize_project() reads no scenario, no simulation, no command-line argument and no environment variable, and it sets no seed. scenarios() chooses the scenarios, and add_data() and add_analyses() set the seeds.

Value

Invisibly, a list with version, home, results and folders. results is the results folder, and folders the named paths of the folders.

The fingerprint of the data

The fingerprint is a data.frame with one row for each file, sorted by file in the C locale:

  • file, the name ⁠<folder name>/<path in the folder>⁠ with /, for example main/sub/d.csv. It never holds the path of the folder.

  • size, the size in bytes.

  • mtime, the modification time in whole seconds since 1970-01-01 UTC, with the fraction of a second cut off. A copy of a file can lose part of that fraction, for example on Windows, and whole seconds stay the same.

Hidden files count. A link to a file gives the size and the time of its target, and list.files() follows a link to a folder. A broken link stops initialize_project(). It also stops when a folder of folders is inside another or is the same folder. It stops when a folder holds or is inside ⁠<version>_results/⁠ or ⁠<version>_cache_gitexclude/⁠, because pbn writes there in each run. A folder elsewhere inside home is allowed.

A file that changed in place, and kept its size and the second of its modification time, is not seen. A copy that does not keep the modification times looks like changed data, so the cache computes the data again. file.copy(..., copy.date = TRUE) keeps them.

Fake real data

The real data of a project MAY be on a server only. Its folders on this computer MAY then hold fake files in the formats of the real data. Then the code that reads the real data runs here, and check_one_file() has results to compare. In a project that is not one-file, give fake_real_data = TRUE in the run script of such a computer. A one-file project gets the same labels without it, see the section The folder fake/. It is about the scenario "real" only:

  • The manifest of the real results gets fake_real_data = TRUE. It is FALSE without the flag. A fake scenario has no such field.

  • The run log says that the scenario real ran on fake real data, in the sections Run and History. The sections Data and Exclusions name the scenario ⁠real (fake real data)⁠.

  • make_outputs() writes the output of "real" as fake output, into ⁠output_fake_data/⁠ of its folder with the prefix fake_data_, and stamp_fake() marks its figures. It deletes an old ⁠output/⁠ there.

  • show_blocks() and show_block() print ⁠FAKE REAL DATA⁠.

The argument decides only what save_results() writes into the manifest. make_outputs(), stamp_fake(), show_blocks() and show_block() read fake_real_data from the manifest of the real results on the disk. So an R session without the argument still marks such results, and an R session with it never marks results from real data.

  • The rule real_results_are_fake of check_project() warns while such real results are on the disk.

read_results() reads such results as usual. The file of to_one_file() never gives fake_real_data, because the server holds the real data. Project code reads the flag with real_data_is_fake(). fake_real_data = TRUE together with generated stops.

The folder fake/

A one-file project is a project whose run script ⁠<version>_run.R⁠ gives one_file_home in a top-level call pbn::initialize_project(). pbn finds this from the parse of the run script, and evaluates nothing. In a one-file project on this computer, the scenario "real" is in ⁠<version>_results/fake/⁠, and not in ⁠<version>_results/real/⁠:

  • save_results(), read_results(), make_outputs(), show_block(), txt(), update_blocks(), check_one_file() and verify() read and write the scenario "real" in ⁠fake/⁠. No function of pbn creates ⁠real/⁠ there.

  • ⁠real/⁠ holds only the real results that come back from the server.

  • one_file_home says that the data on this computer are fake. So pbn writes fake_real_data = TRUE into the manifest of ⁠fake/⁠, and the labels of the section Fake real data apply. The call MUST NOT give fake_real_data = TRUE, and it stops.

⁠fake/⁠ stands in for the real results. It is not one of the fake scenarios of CFG$scenarios, which have planted effects and an ⁠expect_<scenario>()⁠ function. So scenarios() refuses the name fake.

The file of to_one_file() calls initialize_project() without one_file_home, and the server has no run script. So on the server the scenario "real" is in ⁠real/⁠, as in a project that is not one-file.

Paths of the server

Give one_file_home and one_file_folders together, or neither. A project that never goes to a server gives neither. The run script holds the paths, and a commented line ⁠# pbn::to_one_file()⁠ follows the call:

pbn::initialize_project(
  version = "v01",
  home = ".",
  folders = c(main = "../data"),
  one_file_home = "N:/durable/project",
  one_file_folders = c(main = "N:/durable/data")
)
# pbn::to_one_file()

Write both values as literal strings: one_file_home as one string, and one_file_folders as one string or as c() of strings. Only then does the md5 of the run script leave them out, because a value that is code could change the results. See the section The md5 of the run script.

The paths are text only. initialize_project() stops on one of the two without the other, and on a folder of folders that one_file_folders does not name, or the reverse. It checks no folder on the disk and uses no path in the run. It drops a final / or ⁠\⁠ of each path, as the section Details says, and changes nothing else. The paths never go into the manifest, a cache key or the run log.

The md5 of the run script

manifest$source_md5 holds the md5 of ⁠<version>_run.R⁠ without the text that cannot change the results and that a project adds for the server:

  • each argument one_file_home and one_file_folders of a top-level call pbn::initialize_project() with a literal value, from the comma before its name to the end of its value. A literal value of one_file_home is one string constant. A literal value of one_file_folders is one string constant, or a call c() whose arguments are each one string constant, with or without a name. pbn reads this from the parse data and evaluates nothing.

  • each line that holds only a comment with a call of to_one_file() or check_one_file() without arguments, for example ⁠# pbn::to_one_file()⁠, with its line end. The call MAY have ⁠pbn::⁠ and any spaces.

So the results of a run before such an edit stay current. A run script without such text has the md5 of its bytes, as before. An argument without a comma before it, for example the first argument of the call, stays in the md5, and so does an argument with another value, for example paste0(base, "/a"), a name or a block { }. Such a value counts as code: its edit makes the results of an earlier run older than the code. to_one_file() works with such a value too. The md5 of each other file is the md5 of its bytes.

One file

The file of to_one_file() calls initialize_project() with generated, a list with these elements:

  • project, the name of the project folder on the computer that made the file. The run log names the project with it.

  • source_md5, the md5 of the run script and of each file of the functions folder on that computer. The manifest stores it.

  • code, the code of the functions folder as one quoted block, in the order that org sources the files.

With generated, initialize_project() reads no pbn.yml, needs no functions folder, and checks no code lines. It evaluates code in env in the place of the source of the functions folder. A use of the cache then does not check the data_*.R files on the disk, because the code is in the file.

See Also

vignette("pbn"), which builds and runs a small fake project.

Other project setup: create_project(), end_unless_real(), folder(), new_version(), real_data_is_fake(), rules(), scenarios()

Examples

home <- file.path(tempdir(), "pbn_initialize_example")
dir.create(file.path(home, "v01_functions"), recursive = TRUE)
writeLines("extends: house_2026_11_25", file.path(home, "pbn.yml"))
writeLines(
  "CFG <- list(scenarios = data.frame(scenario = c('real', 'null'), sims = c(1, 3)))",
  file.path(home, "v01_functions", "_cfg.R")
)

env <- new.env()
p <- pbn::initialize_project(
  version = "v01",
  home = home,
  folders = c(main = file.path(home, "data")),
  env = env
)
p$results
pbn::folder("main")
env$CFG$scenarios

unlink(home, recursive = TRUE)

Write the filled-in checklist of each reporting guideline

Description

make_checklists() writes one Markdown table for each checklist file ⁠guidelines/<x>.yml⁠, with the status of each item in the manuscript. An item gets ⁠numbers found⁠ only when each formatted string of each block that names it occurs in the manuscript text.

Usage

make_checklists(version = NULL, manuscript = NULL, home = NULL)

Arguments

version

The version, for example "v02". The default is the version of the last initialize_project() in this R session.

manuscript

The path of one .md or .docx file, relative to the working folder. The default NULL is each file ⁠<stem>.md⁠ with a file ⁠<stem>.qmd⁠ in ⁠manuscript/built/<version>/resources/⁠ of home when that folder exists and pbn.yml extends house_2026_12_02 or later. The other .md files there are notes, such as DISPLAY.md. Else it is each .md file in ⁠manuscript/built/<version>/⁠. The files checklist_*.md are left out.

home

The project folder. The default is the folder of the last initialize_project() of version in this R session, and else the working folder.

Details

The items come from ⁠guidelines/*.yml⁠, after the key design of each file, as check_project() reads them. A block names its items in the argument items of block() in ⁠<version>_functions/blocks.R⁠, which make_checklists() reads without running code.

The formatted strings of a block are its formatted value, as txt() gives it. That is the raw value of the real blocks.qs2 of the version, through the formatter of the block. So a change of a formatter needs no update_blocks(). A formatter that returns a character vector gives each element. A formatter that returns a data.frame gives each cell of each row, row by row, with each cell as as.character() gives it. An NA string is never found.

The text of a .md file is its lines. A heading is a line that starts with 1 to 6 ⁠#⁠ and a space, outside a fenced code block. The text of a .docx file is in word/document.xml, which utils::unzip() reads. Each paragraph ⁠<w:p>⁠ is one line, the contents of its ⁠<w:t>⁠ runs joined with no space. A heading is a paragraph whose style w:pStyle starts with Heading. The text before the first heading of a file is under the name of the file.

The search normalises the text and each string in 7 steps, in this order. It changes ⁠<br>⁠, ⁠<br/>⁠ and ⁠<br />⁠ to a space. It removes each other HTML tag, which is <, a letter, then letters and digits, and optional attributes after a space, then > or ⁠/>⁠. It decodes ⁠&lt;⁠, ⁠&gt;⁠, ⁠&nbsp;⁠ and ⁠&amp;⁠. It removes the Markdown backslash before *, <, >, ⁠_⁠, [ and ⁠]⁠. It changes U+00A0 and U+2009 to a space. It changes each run of white space to one space, and it trims the ends. It keeps the minus sign U+2212 and the case of each letter. So the Markdown ⁠p \< 0.001⁠ matches the string p < 0.001.

A string is found when it occurs in the text of all files, joined line by line. The column Reported in names each heading whose section holds one of the strings of the item, joined by ⁠; ⁠.

For each checklist, make_checklists() writes ⁠manuscript/built/<version>/checklist_<id>.md⁠ in home, and it creates that folder when it is absent. It writes no other file. From the set house_2026_12_02 of pbn.yml, ⁠manuscript/built/<version>/resources/⁠ is the layout of render_built(). When it exists, make_checklists() writes two files instead:

  • ⁠resources/checklist_<id>.md⁠, the same table.

  • ⁠manuscript/built/<version>/checklist_<id>.docx⁠, which Pandoc writes from that .md file. The styles come from resources/reference.docx when it exists. Pandoc comes from rmarkdown::pandoc_convert() when rmarkdown finds it, and else from ⁠quarto pandoc⁠.

The table has the columns Section, Item, Recommendation, Reported in and Status. The Recommendation is the full key text of the item. The Status is one of:

  • ⁠numbers found⁠: a result item, and each string of each of its blocks occurs in the text. A reader still confirms that the text answers the item.

  • ⁠numbers missing: <string>⁠: a result item, and ⁠<string>⁠ is the first string that the text does not hold. The blocks are in the order of blocks.

  • ⁠no block⁠: a result item that no block names.

  • reported: a prose or an author item whose entry has the key reported_in.

  • ⁠to fill⁠: a prose or an author item without the key reported_in.

  • ⁠not applicable: <reason>⁠: an item of any kind whose entry has the key not_applicable: "<reason>". make_checklists() reads no block of such an item.

A project copy of a checklist file MAY give an entry the key not_applicable. Its value is one string: the reason why the item does not apply to the project. The checklist schema of the methods repository does not have this key. Only the rule set house_2026_11_28 or later of pbn.yml has it. Under an older set, the rule guidelines_valid of check_project() fails it, and make_checklists() stops on it.

From the rule set house_2026_12_02, a prose or an author entry of a project copy MAY have the key reported_in. Its value is one string: the location in the manuscript that the authors give, such as "Methods, Statistical analysis; Figure S1". make_checklists() writes it in the column Reported in. Under an older set, guidelines_valid fails the key, and make_checklists() stops on it.

The files checklist_*.md are never part of the text. A manuscript path whose name matches checklist_*.md is an error.

make_checklists() stops in each of these cases:

  • a block of block() has no string format or no literal items.

  • a block that names a result item is not in the real blocks.qs2, or that file is missing.

  • a checklist file breaks the schema of check_project().

  • an entry has the key not_applicable, and the rule set of pbn.yml is older than house_2026_11_28.

  • an entry has the key reported_in, and the rule set of pbn.yml is older than house_2026_12_02.

  • ⁠resources/⁠ exists, the set is house_2026_12_02 or later, and ⁠resources/⁠ holds no file ⁠<stem>.md⁠ with a file ⁠<stem>.qmd⁠ other than checklist_*.md.

  • ⁠resources/⁠ exists, and pbn.yml is missing or not valid, as for check_project().

  • ⁠resources/⁠ exists, the set is house_2026_12_02 or later, and neither rmarkdown with Pandoc nor Quarto is there to write the .docx.

Value

The table of all checklists, invisibly. It is a data.frame with one row per item and the columns Guideline (the key id), Section, Item, Recommendation, Reported in and Status. Its cells are the text without the Markdown escapes of the files.

See Also

block(), txt(), check_project().


Write the output of the real data and of chosen fake scenarios

Description

make_outputs() calls the output function of the project on the results of "real", and of each fake scenario with output = TRUE in CFG$scenarios. The files of a fake scenario go to their own folder, and their names start with fake_data_.

Usage

make_outputs(fn, scenarios)

Arguments

fn

The output function of the project, ⁠function(results, dir)⁠. It gets the results of one scenario from read_results(), and writes its files into the folder dir, for example with ggplot2::ggsave().

scenarios

The scenarios of the run, from scenarios().

Details

Call initialize_project() first. For each scenario of scenarios, make_outputs() does this:

  • "real": it calls fn(results, dir) with ⁠dir = <version>_results/real/output/⁠. In a one-file project, the folder is ⁠fake/⁠ in the place of ⁠real/⁠, see the section The folder fake/ of initialize_project(). The output is fake output when the manifest of the real results on the disk has fake_real_data TRUE. It then goes to ⁠output_fake_data/⁠ of that folder, as for a fake scenario below. The manifest decides, and never the argument fake_real_data of initialize_project() in this R session. make_outputs() deletes the other of the two folders of "real" with one printed line, so no output of an earlier run on other data stays.

  • A fake scenario with output = TRUE: it calls fn with ⁠dir = <version>_results/<scenario>/output_fake_data/⁠. Then it renames each file in dir that fn wrote, so that the name starts with fake_data_. It stops when a new name equals the name of another file in dir. It ignores the case of the letters, as Windows and macOS do. The results of a scenario with more than 1 simulation are the stacked results, with a column sim in each data.frame.

  • A fake scenario without output = TRUE: nothing.

save_results() deletes ⁠output/⁠ and ⁠output_fake_data/⁠ of each scenario that it writes, so no output of an earlier run stays beside new results. Before it calls fn, make_outputs() deletes the folder dir and creates it again. So no file of an earlier run stays. Keep no other file in that folder. It stops when the folder is still there afterwards, for example because another program holds a file open on Windows. It tries to create the folder 8 times, with pauses that double from 0.5 seconds to 8, about 30 seconds in all, because a network drive of Windows keeps a folder that was just deleted "pending delete" while another program holds it. The folder counts as created only when pbn can write a file into it. It stops after the eighth try, and the error names the folder and what R said. After each scenario, it prints one line with the folder and the number of files.

After save_results() in the same R session, make_outputs() adds its files, its seconds and the number of warnings of fn for each scenario to the run log ⁠<version>_results/run.md⁠. A warning still reaches the console, and the log holds no text of it. When make_outputs() stops, the result of the log says so, and the errors file of the log holds the error. In another R session it does not change the run log.

fn MUST NOT change an object of the functions folder in place, for example with the index that a data.table subset CFG$table[x == 1] adds. The next call of fn or of an expect_ function in this R session would see the change. make_outputs() compares these objects before and after each call of fn, with the rules of the check of add_analyses(). A change fails the scenario, with the first element that changed, for example CFG$table.

make_outputs() skips a scenario with one printed line when its results.qs2 does not exist, or when its check.csv holds an assertion that did not pass. Then it deletes the output folder of the scenario, so no output of an earlier run stays beside absent or failed results. The line says so. It does not touch a scenario that is not in scenarios. A "real" without check.csv is not skipped, because expect_real() is optional. make_outputs() also skips "real" when its manifest$failed_fake_checks names a fake scenario with a failed assertion. read_results() has the same rule.

When fn stops for one scenario, make_outputs() stops with an error that names the scenario. The output of the scenarios before it stays.

fn MUST write into dir only. Around each call for a fake scenario, make_outputs() lists the path, the size and the modification time of each file in ⁠<version>_results/⁠ outside dir. It also lists the md5 of each file modified in the last 2 seconds. When fn added, changed or removed one of them, make_outputs() deletes the added files and stops with the paths. It does not restore a changed or a removed file. It does not check the call for "real", or files outside ⁠<version>_results/⁠.

A figure of fake data carries the label "FAKE DATA" when the output function calls stamp_fake(). A table or a text file has the name prefix fake_data_ and the folder ⁠output_fake_data/⁠ only. The check_project() rule fake_data_names fails a file in ⁠output_fake_data/⁠ without the prefix, and a file with the prefix in another folder.

Value

Invisibly, a data.frame with the columns scenario and file, one row for each file written. file is relative to the project folder.

See Also

end_unless_real() for output code after the run that is not in a function.

Other output: copy_outputs(), panel_numbers(), plot_dag(), plot_path_model(), render_built(), stamp_fake()

Examples

# See vignette("pbn"), which writes a figure for "real" and for a fake
# scenario.

Start a new version of a project

Description

new_version() freezes the version from and copies its run script and its functions folder to the version to. The project then passes the rule frozen_versions_unchanged of check_project().

Usage

new_version(from = "v01", to = NULL, home = ".")

Arguments

from

The version to copy, "v" and two digits, for example "v01".

to

The new version, or NULL, the default, for the version after from. For "v01" that is "v02". After a manual manuscript ⁠manuscript/manual/vNN_<INITIALS>.docx⁠, to is v(NN+1), as the rule manual_not_ahead of check_project() says.

home

The project folder.

Details

new_version() does these steps in this order:

  1. It freezes from with freeze_version(), when ⁠<from>_frozen.md5⁠ does not exist. When it exists and no file of from changed after it, new_version() leaves it as it is.

  2. It copies ⁠<from>_run.R⁠ to ⁠<to>_run.R⁠, and each file under ⁠<from>_functions/⁠ to ⁠<to>_functions/⁠.

  3. It changes the argument version of the call pbn::initialize_project() in ⁠<to>_run.R⁠ from from to to, and the argument version from of each call pbn::copy_outputs(). It changes no other text of the file.

  4. It adds an entry ⁠<to>_functions/<path>⁠ to each list under ⁠allow:⁠ of pbn.yml that has the entry ⁠<from>_functions/<path>⁠, so the copied file stays allowed. ⁠<path>⁠ MAY be empty, as in ⁠<from>_functions/⁠. It edits two forms of a list, each with or without quotes around an entry and a trailing comment:

    • a flow list ⁠rule: [a, b]⁠ on one line. The new entries go at the end of the list.

    • a block list of lines - a. Each new entry goes on a new line after the old entry.

    A new entry has the quotes of the old entry. A line that has no entry of ⁠<from>_functions/⁠ stays as it is, so each comment stays. The step adds no entry that the list has already. It prints each entry that it adds. After the edit it reads pbn.yml again with the rules of check_project(). When the entries under ⁠allow:⁠ are not the old entries and the new entries, it stops. The error gives the entries to add by hand. One cause is a flow list on more than one line.

  5. It adds the section ⁠## <to>⁠ above the first section ⁠## ⁠ of CHANGELOG.md, with one line that names from. It creates CHANGELOG.md when the file does not exist. When the section is there already, it leaves the file as it is, and its message says so.

It stops before it writes anything in each of these cases:

  • ⁠<to>_run.R⁠, ⁠<to>_functions/⁠ or ⁠<to>_frozen.md5⁠ exists. The error names each one.

  • ⁠<from>_run.R⁠ or ⁠<from>_functions/⁠ does not exist.

  • from is not the newest version of the project. The error names the newest.

  • to is not newer than each version of the project.

  • ⁠<from>_frozen.md5⁠ exists, and a file of from changed, came or went after it. The error names each file. Put the files back, or record the change as intended with freeze_version().

  • ⁠<from>_run.R⁠ has no call pbn::initialize_project() whose argument version is the string from.

  • pbn.yml exists, and check_project() cannot read its rules.

When a step stops after new_version() wrote something, it removes each file and folder that the call created, also ⁠<from>_frozen.md5⁠. It writes CHANGELOG.md and pbn.yml back as they were. So a second call can start again.

Value

Invisibly, to.

See Also

Other project setup: create_project(), end_unless_real(), folder(), initialize_project(), real_data_is_fake(), rules(), scenarios()

Examples

home <- file.path(tempdir(), "pbn_new_version_example")
dir.create(home)
pbn::create_project(home = home)
pbn::new_version("v01", home = home)
pbn::check_project(home)

unlink(home, recursive = TRUE)

Draw a table of numbers under a figure with the same x scale

Description

panel_numbers() draws a table of numbers as a ggplot, with a full outline on each cell. Put it under a figure with the same xlim with patchwork, so each column of the table stands under its x position.

Usage

panel_numbers(d, xlim, header, corner, size, label_width = 150, base_size = 14)

Arguments

d

A data.frame with one row for each cell. The column x is the column of the cell, an integer from 1. The column row is its row, a factor with the bottom row as its first level. The column label is the text of the cell.

xlim

The limits of the x scale, as in the figure above the table.

header

The text of the header row, one string for each column of d$x, so length(header) MUST be max(d$x).

corner

The text of the cell left of the header row, above the row labels.

size

The size of the text in mm, as in ggplot2::geom_text(). For a text size in points, give points / ggplot2::.pt.

label_width

The width in points of the column of row labels. It stands left of the panel, in the space of the y axis.

base_size

The base size of ggplot2::theme_void().

Value

A ggplot.

See Also

Other output: copy_outputs(), make_outputs(), plot_dag(), plot_path_model(), render_built(), stamp_fake()

Examples

if (requireNamespace("ggplot2", quietly = TRUE)) {
  d <- data.frame(
    x = rep(1:3, times = 2),
    row = factor(rep(c("B", "A"), each = 3), levels = c("B", "A")),
    label = c("n = 10", "n = 12", "n = 9", "n = 20", "n = 18", "n = 21")
  )
  q <- panel_numbers(
    d,
    xlim = c(0.5, 3.5),
    header = c("Week 1", "Week 2", "Week 3"),
    corner = "Group",
    size = 10 / ggplot2::.pt
  )
}

Draw a causal diagram (DAG) as rounded boxes and arrows

Description

plot_dag() draws the assumptions of a causal model as rounded boxes, arrows and one legend of the kinds of box. A DAG carries no estimates, so for arrows with estimates use plot_path_model().

Usage

plot_dag(
  nodes,
  edges,
  kinds = c(main = "Exposure, mediator, outcome", adjusted = "Adjusted for", not_adjusted
    = "Not adjusted for", unmeasured = "Unmeasured"),
  box_width = 1.15,
  box_height = 0.42,
  corner = 0.1,
  text_size = 4,
  xlim = NULL,
  ylim = NULL,
  arrow_length = 8,
  arrow_linewidth = 0.5,
  base_size = 13
)

Arguments

nodes

A data.frame with one row for each box. The column id is a unique name, x and y are the centre of the box, label is its text and kind is one of names(kinds). The optional column h is the half height of each box, and replaces box_height for that box.

edges

A data.frame with one row for each arrow. The columns from and to are values of nodes$id. A column label gives an error. Zero rows draw the boxes and the legend with no arrow.

kinds

A named vector of legend labels, in legend order. Each name MUST be one of the four house kinds:

  • main, with the fill ⁠#EAF1F8⁠.

  • adjusted, with the fill grey80.

  • not_adjusted, with a white fill.

  • unmeasured, with a white fill and a dashed border.

box_width

The half width of a box, in the units of x.

box_height

The half height of a box, in the units of y.

corner

The radius of the round corner of a box.

text_size

The size of the box text in mm, as in ggplot2::geom_text().

xlim, ylim

The limits of the plot. NULL gives the range of the boxes plus 0.2 on each side.

arrow_length

The length of an arrowhead in points.

arrow_linewidth

The line width of an arrow.

base_size

The base size of ggplot2::theme_void().

Details

Each arrow runs on the line between two box centres, from the edge of one box to the edge of the other. The two boxes of an arrow MUST NOT overlap or touch. Each nodes$id MUST be unique, and each x and y MUST be a number. An arrow from an unmeasured node is dashed. The legend at the bottom shows the fill and the border of each kind that nodes$kind uses, in the order of kinds.

Value

A ggplot.

See Also

Other output: copy_outputs(), make_outputs(), panel_numbers(), plot_path_model(), render_built(), stamp_fake()

Examples

if (requireNamespace("ggplot2", quietly = TRUE)) {
  nodes <- data.frame(
    id = c("a", "m", "y"),
    x = c(0, 2.5, 5),
    y = c(0, 1.5, 0),
    label = c("Exposure", "Mediator", "Outcome"),
    kind = "main"
  )
  edges <- data.frame(from = c("a", "m", "a"), to = c("m", "y", "y"))
  q <- plot_dag(nodes, edges)
}

Draw a fitted path diagram as rounded boxes and labelled arrows

Description

plot_path_model() draws a fitted path model: one rounded box for each variable, and one arrow with its estimate for each path. For a causal diagram with no estimates, use plot_dag().

Usage

plot_path_model(
  nodes,
  edges,
  box_width = 0.85,
  box_height = 0.32,
  corner = 0.1,
  text_size = 4.4,
  label_size = 3.6,
  xlim = NULL,
  ylim = NULL,
  arrow_length = 9,
  arrow_linewidth = 0.6,
  base_size = 13
)

Arguments

nodes

A data.frame with one row for each box. The column id is a unique name, x and y are the centre of the box and label is its text. The optional column h is the half height of each box, and replaces box_height for that box.

edges

A data.frame with one row for each arrow. The columns from and to are values of nodes$id. The column label is the estimate of the arrow, and MUST NOT be NA or empty. The optional columns label_x and label_y give the position of the text, and hjust and vjust its justification. Without them, the text is centred on the midpoint of the arrow. With the optional column title, ggtext draws the title in bold on the first line and label below it. A title can hold markdown, and a &, < or * in label prints as itself. An NA or blank title gives no title line.

box_width

The half width of a box, in the units of x.

box_height

The half height of a box, in the units of y.

corner

The radius of the round corner of a box.

text_size

The size of the box text in mm, as in ggplot2::geom_text().

label_size

The size of the arrow text in mm, as in ggplot2::geom_text().

xlim, ylim

The limits of the plot. NULL gives the range of the boxes plus 0.2 on each side. An arrow text outside the limits is cut.

arrow_length

The length of an arrowhead in points.

arrow_linewidth

The line width of an arrow.

base_size

The base size of ggplot2::theme_void().

Details

Each arrow runs on the line between two box centres, from the edge of one box to the edge of the other. The two boxes of an arrow MUST NOT overlap or touch. Each nodes$id MUST be unique, and each x and y MUST be a number. Each box has the fill ⁠#EAF1F8⁠, and the figure has no legend.

Value

A ggplot.

See Also

Other output: copy_outputs(), make_outputs(), panel_numbers(), plot_dag(), render_built(), stamp_fake()

Examples

if (requireNamespace("ggplot2", quietly = TRUE)) {
  nodes <- data.frame(
    id = c("a", "m", "y"),
    x = c(0, 2.5, 5),
    y = c(0, 1.5, 0),
    label = c("Exposure", "Mediator", "Outcome")
  )
  edges <- data.frame(
    from = c("a", "m", "a"),
    to = c("m", "y", "y"),
    label = c("0.50 (0.10 to 0.90)", "0.20 (0.05 to 0.35)", "0.10")
  )
  q <- plot_path_model(nodes, edges, ylim = c(-0.8, 2.2))
}

Show the progress inside one analysis

Description

progress() shows how far a long analysis is, for example a bootstrap loop, on the line of its scenario in the display of run_plan(). Outside a run of run_plan() it only checks its arguments.

Usage

progress(done, total, label = NULL)

Arguments

done

The number of steps done, one number of 0 or more.

total

The number of steps of the analysis, one number of 1 or more.

label

Optional. A short text, for example "bootstrap".

Details

Call progress() in the loop of an action function. The line of the scenario then shows the kind of the analysis, the values of its extra dimensions, label, done/total and the percent. When at least 3 steps and at least 10% of the steps are done, it also shows the time left. That time comes from the rate of the steps of this analysis. The count of the finished analyses of the scenario does not change.

After the first failed analysis of the run, no new analysis starts, and an analysis that runs goes on to its end. Its calls of progress() still show.

progress() drops a call less than 0.5 seconds after the last one that it showed. So a call in each pass of a fast loop costs little. It checks its arguments at each call, also outside run_plan(), so a wrong argument stops the analysis however fast it runs.

Apart from the check of its arguments, progress() does nothing in these cases:

  • outside run_plan(), for example when you step through an analysis by hand, or call the action function yourself.

  • in a data function.

  • in a forked child process, for example inside parallel::mclapply(). Several children would write to the one connection of the worker at the same time. Call progress() in the loop of the analysis itself, for example between chunks of the replicates, as the example shows.

Value

NULL, invisibly.

See Also

vignette("pbn"), whose section Progress shows the display.

Other plan: add_analyses(), add_data(), cohort_data(), get_data(), run_plan()

Examples

fit_boot <- function(data, argset) {
  n_boot <- 200
  chunks <- split(seq_len(n_boot), ceiling(seq_len(n_boot) / 50))
  est <- numeric(0)
  for (chunk in chunks) {
    # With forks, for example parallel::mclapply(chunk, ...), call
    # progress() here, between the chunks.
    est <- c(est, vapply(chunk, function(b) {
      return(mean(sample(data$d$x, replace = TRUE)))
    }, numeric(1)))
    pbn::progress(length(est), n_boot, "bootstrap")
  }
  return(data.frame(estimate = mean(data$d$x), se = stats::sd(est)))
}
# Outside run_plan(), progress() does nothing, so this call returns the
# value at once.
fit_boot(list(d = data.frame(x = stats::rnorm(20))), list())

Read the results object of a project version

Description

read_results() reads the results.qs2 of one scenario, and the results_gitexclude.qs2 beside it, the files that save_results() writes. The default reads the real results.

Usage

read_results(version, scenario = "real", sim = NULL, home = ".")

Arguments

version

The version, for example "v01".

scenario

The scenario. The default is "real".

sim

NULL, or the number of one simulation.

home

The project folder.

Details

With sim = NULL, read_results() reads ⁠<home>/<version>_results/<scenario>/results.qs2⁠. That is the results of a scenario with 1 simulation, or the simulations that save_results() stacked. With a number k, it reads ⁠<home>/<version>_results/<scenario>/sims_gitexclude/sim_<kkkk>.qs2⁠, where ⁠<kkkk>⁠ is k with four digits. git ignores that folder, so a clone of the repository has no such file. Then read_results() stops, and the error says to run the scenario with run_plan() and save_results(). For a scenario with 1 simulation, sim = 1 reads its results.qs2, the results of that simulation. The section The files of save_results() shows each file.

In a one-file project, ⁠<scenario>⁠ is fake for the scenario "real". So read_results(version) there reads ⁠<version>_results/fake/⁠. The section The folder fake/ of initialize_project() gives the rule.

read_results() stops when ⁠<home>/<version>_results/<scenario>/check.csv⁠ exists and holds a value of pass that is not TRUE, also when it reads one simulation. It also stops when that file holds no assertion, or has no column pass that R can read. save_results() still writes such results, so that you can find the fault. The error names the file and how to read it with qs2::qs_read().

For "real", read_results() also stops when manifest$failed_fake_checks names a fake scenario. save_results() writes into it each fake scenario of the same run with a failed assertion. The real data and the fake scenarios run through the same code. So a fake scenario with a failed assertion can show a fault in the code of the real results. The error names each such scenario, the path of its check.csv and the fix.

The run that writes the real results writes this record. A run of "real" alone records no fake scenario with a failed assertion. A later run of a fake scenario alone does not change the record of the real results. Real results of pbn 2026.11.24 or older have no failed_fake_checks, and read_results() reads them as before.

read_results() returns one list with the elements of both files. The order is that of a results object: manifest, exclusions, and the analysis kinds in the order of manifest$analyses. These rules apply to results_gitexclude.qs2, and to ⁠sim_<kkkk>_gitexclude.qs2⁠ for one simulation:

  • When the manifest names kinds in it and the file is missing, it returns the elements of the results file. A clone of the repository has no such file. It gives one warning that names the missing kinds and the file.

  • It stops when the file holds other kinds than the manifest names, also when the manifest names none.

A manuscript MUST read the real results only. check_project() fails a call in ⁠manuscript/built/⁠ that gives a scenario other than "real".

Value

The results object, a named list. See save_results().

See Also

Other results: check_results(), render_run(), save_results()

Examples

# See the example of save_results().

Whether the real data of this run are fake

Description

real_data_is_fake() returns TRUE when the scenario "real" reads fake files in the formats of the real data, and FALSE otherwise. A project uses it to choose a setting, for example fewer imputations on a computer without the real data.

Usage

real_data_is_fake()

Details

The value comes from the last initialize_project() of this R session:

  • TRUE in a one-file project on its own computer, because its run script gives one_file_home. See the section The folder fake/ of initialize_project().

  • TRUE with fake_real_data = TRUE.

  • FALSE in the file of to_one_file() on the server.

  • FALSE in a project with neither.

  • In the run of the file that check_one_file() makes on this computer, the value of the R session that calls check_one_file(). In a one-file project it is TRUE. So the run of the project and the run of the file choose the same settings, and their results can agree.

initialize_project() sets the value before it sources the functions folder, so a top-level call in ⁠_cfg.R⁠ can read it:

n_impute <- if (pbn::real_data_is_fake()) 2L else 20L

real_data_is_fake() stops when no initialize_project() of this R session set the value, also after a call that stopped. It never guesses FALSE, because on a computer with fake data that guess starts the long settings of the server.

Value

TRUE or FALSE.

See Also

Other project setup: create_project(), end_unless_real(), folder(), initialize_project(), new_version(), rules(), scenarios()


Render the built manuscript of a version

Description

render_built() renders each .qmd file of ⁠manuscript/built/<version>/resources/⁠ with Quarto. It then moves each .docx file that the render wrote to ⁠manuscript/built/<version>/⁠, so the top of that folder holds only what a reader opens.

Usage

render_built(version, home = ".")

Arguments

version

The version, such as "v02".

home

The top folder of the project. The default "." is the working directory.

Details

render_built() runs ⁠quarto render <file>⁠ for each .qmd file, in name order, with ⁠resources/⁠ as the working directory. Quarto names the output after the input. So after the render of ⁠<stem>.qmd⁠, render_built() moves ⁠resources/<stem>.docx⁠ to the top when it exists, over a file of the same name. A .docx file without a .qmd file of the same stem never moves, such as reference.docx or the Word lock files ⁠~$*⁠. The rendered .md files and the other outputs stay in ⁠resources/⁠.

The layout of ⁠manuscript/built/<version>/⁠ is then:

  • at the top: the .docx files, the copies of copy_outputs() and the folder ⁠resources/⁠.

  • in ⁠resources/⁠: everything else, such as the .qmd and .md files, ⁠_setup.R⁠, references.bib, reference.docx and notes.

The rule built_layout of check_project() fails another file at the top. make_checklists() reads each ⁠<stem>.md⁠ of ⁠resources/⁠ that has a ⁠<stem>.qmd⁠.

render_built() stops when ⁠resources/⁠ is missing or holds no .qmd file, and when quarto is not on the PATH. It also stops when a render ends with a status other than 0. The .docx file of that render does not move, and the files after it do not render.

Value

The paths of the moved .docx files, invisibly.

See Also

Other output: copy_outputs(), make_outputs(), panel_numbers(), plot_dag(), plot_path_model(), stamp_fake()

Examples

home <- tempfile()
res <- file.path(home, "manuscript", "built", "v01", "resources")
dir.create(res, recursive = TRUE)
writeLines(
  c("---", "format: docx", "---", "", "A paper."),
  file.path(res, "paper.qmd")
)
render_built("v01", home = home)
list.files(file.path(home, "manuscript", "built", "v01"))
unlink(home, recursive = TRUE)

Render the run log to a PDF

Description

render_run() renders the run log ⁠<version>_results/run.md⁠ to ⁠<version>_results/run.pdf⁠ with Quarto and its Typst format. A run never calls it, so a missing Quarto cannot fail a run.

Usage

render_run(version, home = ".")

Arguments

version

The version, for example "v01".

home

The project folder. The default is the working directory.

Details

save_results() writes run.md. render_run() needs the program quarto on the PATH. Quarto holds Typst, so the PDF needs no LaTeX. It stops when run.md does not exist, when Quarto is not installed, or when Quarto fails.

render_run() renders a copy of run.md in a temporary folder, with an A4 page, a 9 point font and narrow margins. So no file of Quarto stays in the results folder, and run.md stays as save_results() wrote it. It then copies run.pdf to a temporary file in ⁠<version>_results/⁠, and renames it to run.pdf. So an interruption never leaves a part of the PDF.

run.pdf is generated output, and run.md is the form for git. Keep run.pdf out of git, for example with the line run.pdf in the .gitignore of the project. pbn does not write that line.

Value

Invisibly, the path of run.pdf.

See Also

vignette("pbn"), which shows the run log of a small fake project.

Other results: check_results(), read_results(), save_results()

Examples

home <- file.path(tempdir(), "pbn_render_example")
dir.create(file.path(home, "v01_results"), recursive = TRUE)
writeLines(
  c("# Run log", "", "| Scenario | Simulations |", "|---|---:|", "| real | 1 |"),
  file.path(home, "v01_results", "run.md")
)
if (nzchar(Sys.which("quarto"))) {
  pbn::render_run("v01", home = home)
}
unlink(home, recursive = TRUE)

Print the rules that check a project

Description

rules() prints each rule of the set that pbn.yml extends, in the order of check_project(). It runs no check and reads no data or results.

Usage

rules(home = ".")

Arguments

home

The top folder of the project. The default "." is the working directory.

Details

For each rule, it prints the name, the level after the changes of pbn.yml, what the rule needs, and the fix of a finding. A rule with parameters, such as loc_per_file, also prints them. The text is the text of the PASS line and of the fix of check_project().

Value

A data.frame, invisibly, with one row for each rule and the columns rule, level, needs, fix and parameters. parameters is "" for a rule without parameters.

See Also

?check_project for the details of each rule.

Other project setup: create_project(), end_unless_real(), folder(), initialize_project(), new_version(), real_data_is_fake(), scenarios()

Examples

home <- tempfile()
dir.create(home)
writeLines("extends: house_2026_12_02", file.path(home, "pbn.yml"))
pbn::rules(home)
unlink(home, recursive = TRUE)

Run a plan

Description

run_plan() runs every analysis of the plnr plan p, in this R session or on workers new R sessions. It stops the run at the first failed analysis, and then it prints each failed analysis with its error.

Usage

run_plan(p, workers = 1)

Arguments

p

A plan from plnr::Plan$new(), with data from add_data() and analyses from add_analyses().

workers

The number of R sessions that run the analyses, one whole number of 1 or more.

Details

With workers = 1, run_plan() calls p$run_all() in this R session.

With workers 2 or more, run_plan() needs the packages future and doFuture. It starts a PSOCK cluster of workers new R sessions with parallel::makePSOCKcluster(). It runs p$run_all() with the foreach path of plnr, on doFuture::registerDoFuture() with the future plan future::cluster on that cluster. A PSOCK cluster does not fork, so it also works on Windows. Each future runs a batch of tasks of plnr on a worker, and each task holds the analyses that get the data of one key. Each worker gets about 4 batches when each data function with arguments has both scenario and sim, or when no data function has arguments. Otherwise each task is a batch of its own.

Each worker starts with the library paths of this R session, from .libPaths(). While it starts the cluster, run_plan() sets the environment variable R_LIBS to these paths, and then it sets R_LIBS back. So a worker also finds a library that this R session added with .libPaths(), for example the temporary library of ⁠R CMD build⁠. Each worker runs with 1 thread. While run_plan() starts the cluster, it sets the environment variables OMP_NUM_THREADS, OPENBLAS_NUM_THREADS and MKL_NUM_THREADS to 1, as it sets R_LIBS. Then it sets them back in this R session. OpenMP and the BLAS libraries OpenBLAS and MKL read them when they start their threads, so the variables MUST be there when the worker starts. The section One thread for each worker gives the rules.

Before the run, run_plan() gives each worker these:

  • the library paths of this R session again, with .libPaths().

  • 1 thread: the three variables again, for a library that the worker loads later, and data.table::setDTthreads(1) when data.table is installed.

  • the packages attached in this R session, in the order of search(), for example data.table after library(data.table) in the run script.

  • the kind of random number generator of this R session, from RNGkind().

  • the paths in org::project, such as org::project$home.

  • the folders of initialize_project(), so that folder() works on the worker. A worker then loads pbn.

A future starts with an empty global environment. initialize_project() sources the functions folder into an environment, .GlobalEnv by default. Each batch takes every object of that environment to the global environment of its worker. A data function and an action function then find CFG and the other functions of the folder. A plnr plan and .Random.seed are left out. Each batch takes a copy of each object, so keep large objects out of that environment.

run_plan() does not copy the R options, for example options(digits = 3), and no other state of this R session. A future sets the option mc.cores to 1. run_plan() removes it on a worker, so parallel::mclapply() in an analysis uses its default number of cores. The output, the messages and the warnings of a worker come to this R session at the end of each batch.

After the run, run_plan() stops the cluster and registers the sequential foreach backend, also after an error. It sets the future plan and the option doFuture.rng.onMisuse back to their values before the run. Each data function and each analysis sets its own seed, so run_plan() turns off the warning of doFuture about random numbers for the run. plnr calls each data function once for each scenario and simulation, see add_data(). Each data function and each analysis sets its own seed before it runs, see add_analyses(). Take a function that depends only on its arguments, the objects of the functions folder such as CFG, the attached packages and the seed. Its results with workers = 1 and with workers = 2 are identical(). A function that reads an R option or another state of the main R session can give other results on a worker. A data.table loses its self-reference on the way back from a worker, and run_plan() gives it a new one with data.table::setalloccol(). It does this for each data.table in a value or in a plain list in a value, at any depth. It does not do this for a data.table in a list column of a data.frame. Such a value MAY differ in identical() between 1 worker and more.

An error in an action function fails that analysis, and an error in a data function fails each analysis that gets the data. pbn saves no results of a run with a failed analysis, so the first failed analysis stops the run. The section Stop at the first failure gives the rules. After the run, run_plan() prints each failed analysis with its name and its full error message with cat(), and then it stops. R cuts an error message at 1000 bytes by default, and cat() does not. The error message of run_plan() gives the number of failed analyses and of the analyses that did not run. It also names the first failed analysis in the order of the plan, and holds its error. pbn cuts that error to keep the message below 900 bytes. When 2 or more analyses fail and all have the same error, the message says so. The results files of an earlier run stay as they are. After initialize_project(), run_plan() writes the run log ⁠<version>_results/run.md⁠ with the failures before it stops. The section The run log of save_results() describes it.

After initialize_project(), run_plan() first replaces the run log with one that says that the run has not finished, and deletes the errors file ⁠<version>_results/run_errors_gitexclude.md⁠. A call of run_plan() without save_results() after it leaves this log.

run_plan() measures the elapsed time of each data step and of each analysis where it runs, also on a worker, and the time of the clock of the computer at its end. The times go to the record of the plan, and save_results() writes them to the run log. They are not in the value, so two runs stay identical().

The value carries the attribute pbn_run, a stamp of the plan. It holds no count of the runs, so two runs of one plan can be identical(). save_results() stops on a value without the stamp of its plan.

run_plan() sets use_foreach of the plan: FALSE for 1 worker and TRUE for more.

After initialize_project(), run_plan() first lists the files of the folders of the project again, with their sizes and modification times. It reads no content of a file. The value carries this fingerprint in its stamp, and save_results() writes it to manifest$data_files.

An analysis that changes the shared data in place fails, also for a change of values such as data$d[1, x := 0]. The error names the data and each changed column. An analysis that changes an object of the functions folder in place fails too. So does an analysis that leaves a new object in the global environment. add_analyses() gives the rules.

An error outside the wrappers of pbn ends the run. Examples are a worker that stops, and an error of plnr or of the backend of the workers. run_plan() then prints the whole error, and writes the run log with it after initialize_project(). It stops with one message that holds the error, cut below 900 bytes, and saves nothing. The future plan, the foreach backend and the options go back as after any run, and the cluster stops.

For a data function with cache = TRUE, run_plan() needs initialize_project() first, and it prints one line for each scenario and simulation. The section Cache of add_data() gives the rules. A data function that returns a cohort::CohortPipeline runs on the worker, and only its data.table and its exclusion table come back. The section A cohort as the data of add_data() gives the rules.

Value

Invisibly, a named list with one element for each analysis of the plan, in the order of the plan. Element i is the value of the action function of analysis i. Give it to save_results().

One thread for each worker

Some packages start threads of their own, for example data.table, fixest, a threaded BLAS and OpenMP code. By default, such a package uses many cores. data.table, for example, uses half of the cores of the computer. With workers 2 or more, each worker would do that, and the computer would run far more threads than cores. So run_plan() makes each worker use 1 thread. There is no argument to change it. An analysis that needs more threads in its worker sets them in its own code, for example data.table::setDTthreads(4) at the top of its action function.

With workers = 1, run_plan() changes no thread setting, and the analyses run with the settings of this R session.

The results of the test projects of pbn are identical() with 1 and 2 workers. pbn does not check this for other code. A threaded BLAS MAY sum in another order with another number of threads. So a matrix product of such a BLAS MAY differ in its last digits between workers = 1 and more workers. With 1 worker it has the threads of this R session, and with more it has 1 thread.

Stop at the first failure

A failed data function makes each analysis of its scenario and simulation fail, and save_results() needs a run without a failed analysis. So no analysis after the first failure can give a result, and run_plan() stops the run there. There is no option to run on. These are the rules:

  • After the first failed analysis, no new data function and no new analysis starts. An analysis whose data failed fails at once, also after the stop, without a call of its action function.

  • With 1 worker, the stop comes directly after the failed analysis.

  • With workers, the failed analysis creates a folder in the temporary folder of this R session. Each worker looks for it before each data function, and at most every 0.5 seconds before an analysis. pbn does not stop an analysis that runs. So the longest delay is the rest of the longest analysis that runs at the time of the failure, plus 0.5 seconds. The batches that did not start still go to the workers, and each of them ends at once.

  • Each analysis that did not run counts as not run. It is not a failure.

The display shows the stop at once, and the run log says that the run stopped early and how many analyses did not run.

Progress

run_plan() shows one line for each scenario: its finished analyses of all its analyses, the failed ones among them, the time since its start, and a note. The note is one of these:

  • "waiting" before the scenario starts, and "done" at its end.

  • "stopping" after the first failed analysis of the run, and "stopped early" with the analyses that did not run at the end.

  • the last text of progress() from an analysis of the scenario, while that analysis runs.

  • otherwise the time left, from the analyses of the scenario that ended without a failure, after at least 3 and at least 10% of them.

The analyses that count the rows do not count. The display replaces the progress bar of plnr. The header of the display in a terminal gives the time since the start of the run. So does the start of each line of a log, for example ⁠pbn: [12m 05s] null 522/1200 analyses, 8m 53s, about 12m left⁠.

In an interactive terminal, the display draws its lines again in place. In RStudio and in another console without ANSI codes, it draws one line again in place. It shows the lines of each scenario at the end. While the display is shown, progressr holds back other output, messages and warnings, and shows them above it.

Without an interactive session, for example with Rscript into a log, in knitr and in testthat, the display only adds lines:

  • nothing in the first 60 seconds of the run, other than the line of the first failed analysis. A short run without a failure adds no line.

  • one line at once when the first analysis fails, also in the first 60 seconds.

  • after 60 seconds, a header, and one line for each scenario that started.

  • one line when a scenario finishes.

  • one line for a running scenario at most every 60 seconds. The line comes only when 10% more of the scenario is done, in analyses or in its last text of progress().

A worker sends the count of its finished analyses at most every 0.5 seconds, and at the end of each scenario and simulation. The display uses progressr with a handler of its own, inside progressr::with_progress(). It sets no progressr handler of the R session, so the handlers that another package sets stay as they are.

See Also

vignette("pbn"), which builds and runs a small fake project.

Other plan: add_analyses(), add_data(), cohort_data(), get_data(), progress()

Examples

CFG <- list(scenarios = data.frame(scenario = c("real", "null"), sims = 2))
p <- plnr::Plan$new()
pbn::add_data(p, "d", fn = function(scenario, sim) {
  return(data.frame(x = stats::rnorm(5)))
})
pbn::add_analyses(
  p,
  pbn::scenarios(CFG),
  name = "mean_x",
  fn = function(data, argset) return(data.frame(mean = mean(data$d$x)))
)
r <- pbn::run_plan(p)
r[["null__sim_0002__mean_x__1"]]

Save the results of a run

Description

save_results() writes one results object for each scenario and simulation of a run, and stacks the simulations. It checks the fake scenarios with their expect_ functions, and writes no results file when an object fails check_results().

Usage

save_results(r, p, scenarios, gitexclude = NULL)

Arguments

r

The value of run_plan() for the plan p.

p

The plan, with data from add_data() and analyses from add_analyses().

scenarios

The scenarios of the run, from scenarios(). They MUST be the scenarios of the analyses of p.

gitexclude

NULL, or the names of the analysis kinds whose results hold data for each person. See the section Two files.

Details

Call initialize_project() first. For each scenario and simulation, save_results() builds one results object, a named list. Its first element is manifest. When a data function returned a cohort::CohortPipeline, the next element is exclusions, the exclusion tables of the cohorts row-bound in the order of add_data(). The column data names the data of each row. The section A cohort as the data of add_data() gives the columns. A plan without a cohort has no element exclusions. Then comes one element for each analysis kind of add_analyses(), under the kind name and in the order of the calls. The scenario "real" has no element of a kind with control = TRUE. The element of a kind holds the values of its analyses for that scenario and simulation, in the order of the plan:

  • When each value is a data.frame, the element is the values row-bound. Each extra dimension of the kind comes first as a column, unless the data.frame has a column of that name already. A data.table stays a data.table. A kind without extra dimensions has the data.frame of its one analysis.

  • When each value is a list of data.frames with the same names, each name once, the element is a named list with these names. Each of its data.frames is the data.frames of that name row-bound, with the rule of a data.frame above. An example is results$sem$estimates and results$sem$fit.

  • Otherwise, a kind without extra dimensions has the value of its one analysis.

  • Otherwise, the element is a named list with one entry for each analysis. Each name is ⁠<name>__<i>⁠, the analysis name without the scenario and the simulation. So the names are the same in each simulation. add_analyses() gives the order of ⁠<i>⁠.

The manifest is a list with these elements:

  • pbn_version and r_version.

  • packages, a named character vector. The names are the attached and loaded packages of this R session that are not base packages, and the values are their versions. qs2 is always in the list, because it writes the file. With 2 or more workers of run_plan(), the list also holds the packages loaded on a worker at the end of the run. An example is the package of a model. With 2 or more workers, this R session also loads doFuture and the packages that it imports, such as future, so the list then holds these too.

  • run_date, the date of the call as YYYY-MM-DD. It has no time, so two runs on one day with the same inputs and packages write the same bytes.

  • version, scenario, sim and sims.

  • settings, the named list of the setting columns of the scenario. It is an empty list when there are none.

  • source_md5, the md5 of ⁠<version>_run.R⁠ and of each file in ⁠<version>_functions/⁠ at any depth, also a file that is not an .R file, named by the path relative to home. The one file that it MAY leave out is ⁠<version>_functions/blocks.R⁠, the blocks of show_block(). initialize_project() leaves it out only when it cannot change the results, which is when each of these holds:

    • it parses.

    • each top-level expression assigns with ⁠<-⁠ or = a name to ⁠function(...)⁠, or blocks to list(...).

    • no other file of the folder assigns one of its names.

    • no other file and no run script uses one of its names.

    Otherwise source_md5 holds it, also when the rule blocks_list of check_project() is warn or off. From the rule set house_2026_11_26, initialize_project() also leaves out ⁠<version>_functions/formatters.R⁠, the formatters of block(), under the same conditions. Its only shape is a name assigned to ⁠function(...)⁠, and only blocks.R MAY use its names. A change of a blocks file of that shape thus keeps the results current. initialize_project() computes the md5 before it sources the files. The cache key of add_data() holds the md5 of the files data_*.R only, so it never held blocks.R. The rule manifest_source needs the run script in source_md5, so save_results() stops when ⁠<version>_run.R⁠ did not exist.

  • For the scenario "real" only, data_files, the fingerprint of the files under the folders of folders of initialize_project() when run_plan() started. It is a data.frame with the columns file, size and mtime. Each file is ⁠<folder name>/<path in the folder>⁠, for example main/sub/d.csv, and never the path of the folder. pbn reads no content of a data file. The section The fingerprint of the data of initialize_project() gives the rules. So the manifest names the data that the run read, also after a change of a file since initialize_project(). The same files in another place, with the same modification times, give the same manifest. save_results() stops for "real" when a folder did not exist when initialize_project() ran.

  • For the scenario "real" only, fake_real_data, TRUE or FALSE: the argument fake_real_data of initialize_project().

  • For the scenario "real" only, failed_fake_checks, a character vector. It holds each fake scenario of the same call of save_results() with a failed assertion, in the order of scenarios. It is empty when each one passed, or when scenarios has no fake scenario. read_results() stops on real results where it is not empty.

  • For a fake scenario only, fake_md5, one md5 of the code of the data functions of add_data(), without their source references. The code is each fn, each step of the steps form, and each function of the functions folder that fn or a step calls. A function counts also when another such function calls it. These are the functions of the cache key of add_data(cache = TRUE).

  • n_rows_data, a named integer vector with the number of rows of each data element. A list of data.frames with one number of rows, for example a list of imputed data sets, has the rows of one of them. Each other element that is not a data.frame has NA.

  • n_rows_lists, a named list with one entry for each data element that is a list of data.frames with 2 or more numbers of rows. The entry is an integer vector with the rows of each data.frame, in the order of the list. Such an element has NA in n_rows_data. The list is empty when no data element is such a list. The rule no_row_per_person checks each of these numbers. The analysis ⁠<scenario>__sim_<kkkk>__pbn_n_rows⁠ of add_analyses() counts them where the data is, also on a worker. The rule no_row_per_person reads it.

  • n_rows_before_exclusions, a named integer vector with the number of rows given to the cohort of each data element, or NA for data without a cohort. no_row_per_person reads it too.

  • n_rows_after_exclusions, the same for the rows after the exclusions: n_after of the last step of the exclusion table. It has a number also when n_rows_data is NA, for example for a mids object.

  • analyses, a data.frame with the columns analysis, control and file: the analysis kinds in the object, and the file of each, "results.qs2" or "results_gitexclude.qs2".

  • data_cache, a data.frame with one row for each data element of add_data() and the columns data, cache, from_cache and cache_key. cache is the argument of add_data(). from_cache is TRUE when run_plan() read the data from the cache. cache_key is the md5 of the cache key, or NA without a cache.

save_results() does these steps in this order. It stops at the first step that fails:

  1. It checks its arguments. It stops when r has no stamp of run_plan() for p. It stops when the settings of scenarios are not the settings in the argsets of p. It stops when a fake scenario has no function ⁠expect_<scenario>(results)⁠ in the environment of initialize_project(), or when an analysis of r failed. In a git repository, it stops when git does not ignore each file that it would write into a folder ⁠sims_gitexclude/⁠. The error names the first 3 of the files that git does not ignore. It writes no results file then, and it writes the run log with its error.

  2. It builds every results object, and the stacked object of each scenario with more than 1 simulation, and checks each with check_results(). On a failure, it prints each failed rule with cat(), writes no results file and stops.

  3. When scenarios holds "real", it first replaces the check.csv of "real" with one failed assertion, ⁠not checked yet⁠. So read_results() refuses the real results of an earlier run, also when save_results() stops before it writes "real". It does steps 3 and 4 for the fake scenarios first, and then for "real". So the manifest of the real results records each fake scenario of the same run with a failed assertion. The element failed_fake_checks holds them. For each scenario, it replaces check.csv with one failed assertion, ⁠not checked yet⁠, so that read_results() refuses the new results until step 4 checks them. It deletes the folders ⁠output/⁠ and ⁠output_fake_data/⁠ of each scenario that it writes, with one printed line. That output belongs to the results of an earlier run. The section Output of the run log then says that this run made no output, until make_outputs() runs. Then it writes the files of the section The files. The files of the scenarios that are not in scenarios stay as they are.

  4. For each scenario with a function ⁠expect_<scenario>()⁠, it calls that function on the results of the scenario. expect_real() is optional. The function MUST return a data.frame with at least one row and the columns assertion, expected, observed and pass. save_results() writes it to ⁠<version>_results/<scenario>/check.csv⁠ and prints it. For "real" without expect_real(), it deletes check.csv. An error, zero rows or another shape is one failed assertion. A change of an object of the functions folder in place, for example CFG, adds one failed assertion that names the first element that changed. The section on these objects in add_analyses() gives the rules. This rule is the same for expect_real() and for the fake scenarios. save_results() writes check.csv to a temporary file in the same folder and renames it, so a reader never sees a part of it.

  5. It writes the run log ⁠<version>_results/run.md⁠, also after a stop in step 2, 3 or 4. The section The run log gives its content.

  6. After every scenario, it stops when a value of pass is not TRUE. It prints each failed assertion in full with cat(), because R cuts an error message at 1000 bytes by default. The error gives the number of failed assertions, their scenarios and the path of check.csv. The files stay, so that you can find the fault, and read_results() stops on them until the assertions pass.

  7. When the functions folder defines blocks, see show_block(), it calls each block function on the results of each scenario of scenarios. It reads them with read_results() and sim = 1. So for a scenario with 2 or more simulations, a block gets simulation 1, and not the stacked results. It writes the values of a scenario to ⁠<version>_results/<scenario>/blocks.qs2⁠, a named list with one value for each block, in the order of blocks. It calls every block on every scenario before it writes a file. A block fails on an error of its function, or on a value that is not a data.frame or a character vector. A block() fails on a raw value that breaks the rule of block(), and blocks.qs2 holds its raw value. This step does not call the formatter. At the first failure, it stops and writes no blocks.qs2. The error is ⁠block <k> "<name>" failed on scenario <s>: <error>⁠. So a block MUST work on the results of each fake scenario too. Without blocks, this step writes nothing. The run log of step 5 does not record this step.

Value

Invisibly, a data.frame of every assertion, with the columns scenario, assertion, expected, observed and pass.

The run log

run_plan() replaces the run log at its start with a short log that says that the run has not finished. A run that ends before the next log, for example when R stops, leaves that log. run_plan() also writes the full log when it stops on failed analyses, and make_outputs() adds its files to it in the same R session. Each run replaces the file, and carries its section History forward. The log is GitHub-flavoured Markdown in ASCII, with these sections in this order:

  • When: the date and the time of the start of the run.

  • Run: the result in one sentence and the scenarios of the run. Then the run date of each other scenario on the disk, from its manifest. Then the versions of R, pbn, plnr and cohort, the number of the other packages, and the number of workers. The manifest of each results file lists the other packages.

  • Failures, only after a failure: the failed analyses with their errors, the number of analyses that did not run after the stop of the run, the failed assertions, and the failed rules of check_results().

  • Scenarios: the simulations and the analyses of each scenario.

  • Data: the cache and the rows of each data element.

  • Exclusions: the exclusion table of simulation 1 of each scenario. A cohort without an exclusion step gets one sentence instead.

  • Assertions: the count for each scenario, and its assertions. For more than 30 assertions, the failed ones only.

  • Output and Files: the files of make_outputs() and the number of warnings of the output function for each scenario, without their text. Then the results files, with their sizes.

  • Timings: seconds on the clock. The wall seconds of each step of the main session, and of each scenario. Then the calls of each data step and analysis kind of each scenario, with the median and the maximum seconds of one call. The share gives its part of the seconds of all data steps and analyses.

  • History: one line for each run of this version, oldest first. Each line gives the start and the result in a few words. It also gives the scenarios, the workers, the wall seconds of run_plan(), save_results() and make_outputs(), and the version of pbn.

The log holds counts, exclusion tables and the rows of check.csv. It never holds the text of an error, because an error message can hold a value of the data. These errors get a number in the log:

  • the error of each failed analysis or data step, one number for each message,

  • the error of an expect_ function that stopped,

  • the detail of each failed rule of check_results(), which can quote a name of the project,

  • the error of save_results() itself, also in the checks of its arguments,

  • the error of the output function of make_outputs().

The file ⁠<version>_results/run_errors_gitexclude.md⁠ holds the full text of each error under its number. In a git repository, pbn writes it only when git ignores it, as the line ⁠*gitexclude*⁠ of .gitignore does. Otherwise the log says that the file is missing. Each run deletes the old file, and pbn writes it only when the run has an error.

A project string outside a table, for example a file name of make_outputs(), is on one line as a code span. A string in a table cell is on one line too. So a line end in a string cannot start a heading or a list item.

Only the sections When, Timings and History change in every run. Two runs of the same code on one day, with the same data and cache, give the same other lines. So put run.md in git, and ⁠git diff⁠ shows the real changes of a run. render_run() renders the log to a PDF.

pbn measures each time with proc.time() in the R session that does the work, also on a worker. A data step gets the time of its function. Data from the cache gets the time of the read. An analysis gets the time of its action function. Each one also records the time of the clock of the computer at its end. A scenario runs from the start of its first data step or analysis to the end of its last one. All workers run on this computer, so their clocks are one clock. With workers, the scenarios overlap, so their seconds do not add up to those of run_plan(). No timing goes to the value of run_plan(), a results file, check.csv or a cache key.

The history is in run.md only. The log at the start of run_plan() adds the line "did not finish" for the run. The full log replaces that line, so each run has one line. A run that R stops keeps its line "did not finish". pbn reads the history from the run.md on the disk. When it cannot read a line, for example after a hand edit, it leaves the line out and prints one line. The run goes on. A deleted run.md starts the history again.

The files

git gets the results of each scenario as one file, results.qs2, and never the results of each simulation. These are the files of ⁠<version>_results/<scenario>/⁠. In a one-file project, the folder of "real" is ⁠<version>_results/fake/⁠, see the section The folder fake/ of initialize_project():

blocks.qs2                 the values of the blocks, on simulation 1
check.csv                  the assertions of expect_<scenario>()
results.qs2                the results, stacked for more than 1 simulation
results_gitexclude.qs2     the kinds of `gitexclude`, stacked the same way
sims_gitexclude/           only for more than 1 simulation
  sim_<kkkk>.qs2           the results of simulation <kkkk>
  sim_<kkkk>_gitexclude.qs2  the kinds of `gitexclude` of simulation <kkkk>

A scenario with 1 simulation has no folder ⁠sims_gitexclude/⁠. Its results.qs2 is the results object of its one simulation. For more simulations, results.qs2 holds the simulations stacked, with the rules of the section Stacking. The name of ⁠sims_gitexclude/⁠ holds gitexclude, so the line ⁠*gitexclude*⁠ of .gitignore keeps it out of git. A clone of the repository thus has no results of one simulation. read_results() with sim reads them.

Before it writes a scenario, save_results() deletes each file in its ⁠sims_gitexclude/⁠, and prints one line when there was one. So no simulation of an earlier run stays, for example after sims became smaller. For a scenario that now has 1 simulation, it deletes the folder.

Before it writes a scenario, save_results() also deletes its blocks.qs2. So a call that stops before step 7 leaves no values of the blocks of an earlier run beside the new results. A block gets the results with the kinds of gitexclude. So a block that shows rows for each person writes them into blocks.qs2. The line ⁠*gitexclude*⁠ of .gitignore does not keep that file out of git.

save_results() stops when a file or a folder that it deletes is still there afterwards, for example because another program holds it open on Windows. The error names the file.

pbn 2026.11.22 and older wrote the results of each simulation to ⁠sim_<kkkk>/results.qs2⁠, and git tracked them. When save_results() writes a scenario with more than 1 simulation, it deletes each folder ⁠sim_<kkkk>/⁠ of that scenario, and prints one line.

Stacking

The stacked results hold every element of the results of simulation 1, in the same order. These rules apply at each depth:

  • A data.frame gets a first column sim, and the rows of the simulations in order. It keeps the class of simulation 1, so a data.table stays a data.table.

  • A list is stacked element by element, and pbn matches the elements by name. So each element of a list MUST have its own name.

  • Each other element becomes a list with one entry for each simulation, named sim_0001, sim_0002 and so on. This includes an atomic vector, a matrix, a factor, a date and NULL.

Stacking stops when two simulations differ in the structure at one path, and the error names the path and the two simulations. It also stops on a data.frame with a column sim, because pbn adds that column.

The manifest is that of simulation 1. In it, sim and n_rows_data are NA, sims is the number of simulations, and stacked is TRUE. The columns from_cache and cache_key of data_cache are NA. The counts n_rows_before_exclusions and n_rows_after_exclusions are NA too, and n_rows_lists is an empty list. The element n_rows_by_sim holds the counts of each simulation. It is a data.frame with one row for each simulation and data element. Its columns are sim, data, n_rows_data, n_rows_before_exclusions and n_rows_after_exclusions. Each data.frame of an entry of n_rows_lists adds a row with the data ⁠<element>[[i]]⁠ and its rows in n_rows_data. The rule no_row_per_person of check_results() reads it.

Two files

save_results() writes the results of the kinds in gitexclude to results_gitexclude.qs2, beside results.qs2, and to ⁠sim_<kkkk>_gitexclude.qs2⁠, beside each ⁠sim_<kkkk>.qs2⁠. The section The files shows them. results.qs2 and ⁠sim_<kkkk>.qs2⁠ hold manifest, exclusions and every other kind. Use gitexclude for a kind with fitted models, imputations or one row for each person. The project's .gitignore MUST hold the line ⁠*gitexclude*⁠, so that git never tracks that file. read_results() reads both files.

These rules apply:

  • save_results() stops before it writes anything when a name in gitexclude is not an analysis kind of p.

  • In a git repository, it also stops when git does not ignore results_gitexclude.qs2.

  • check_results() checks results.qs2 and ⁠sim_<kkkk>.qs2⁠, and not the files of gitexclude.

  • The simulations of the two files are stacked apart, with the rules of the section Stacking.

  • Without kinds in gitexclude, save_results() deletes an old results_gitexclude.qs2 of the scenario, and prints one line. The old ⁠sim_<kkkk>_gitexclude.qs2⁠ files go with the rest of ⁠sims_gitexclude/⁠, see the section The files.

See Also

vignette("pbn"), which builds and runs a small fake project.

Other results: check_results(), read_results(), render_run()

Examples

home <- file.path(tempdir(), "pbn_save_example")
dir.create(file.path(home, "v01_functions"), recursive = TRUE)
dir.create(file.path(home, "data"))
writeLines("extends: house_2026_11_25", file.path(home, "pbn.yml"))
writeLines("# The run script.", file.path(home, "v01_run.R"))
writeLines(
  c(
    "CFG <- list(scenarios = data.frame(scenario = c('real', 'null'), sims = 1))",
    "expect_null <- function(results) {",
    "  data.frame(assertion = 'one row', expected = 1,",
    "    observed = nrow(results$means), pass = nrow(results$means) == 1)",
    "}"
  ),
  file.path(home, "v01_functions", "_cfg.R")
)
env <- new.env()
pbn::initialize_project("v01", home, c(main = file.path(home, "data")), env = env)

scenarios <- pbn::scenarios(env$CFG)
p <- plnr::Plan$new()
pbn::add_data(p, "d", fn = function(scenario, sim) {
  return(data.frame(x = stats::rnorm(5)))
})
pbn::add_analyses(p, scenarios, name = "means", fn = function(data, argset) {
  return(data.frame(mean_x = mean(data$d$x)))
})
r <- pbn::run_plan(p)
pbn::save_results(r, p, scenarios)
names(pbn::read_results("v01", home = home))

unlink(home, recursive = TRUE)

Choose the scenarios of a run

Description

scenarios() checks the scenario table cfg$scenarios and returns it, or the rows of the scenarios in only. The real data is the scenario "real", and each other scenario is fake.

Usage

scenarios(cfg, only = NULL)

Arguments

cfg

The config list of the project, normally CFG from ⁠<version>_functions/_cfg.R⁠. It MUST have the element scenarios.

only

NULL for every scenario, or a character vector of scenario names.

Details

cfg$scenarios MUST be a data.frame with these columns:

  • scenario: unique names that match ⁠^[a-z0-9_]+$⁠. One name MUST be "real". A name MUST NOT be "fake", because in a one-file project the folder ⁠fake/⁠ holds "real", see the section The folder fake/ of initialize_project().

  • sims: the number of simulations of the scenario, a whole number of 1 or more.

  • output: optional. TRUE or FALSE on each row, and FALSE for "real". make_outputs() writes the output of a fake scenario with TRUE. This column is not a setting. It is not in the argsets, in the key of the cache or in manifest$settings.

Each other column is a setting of the scenario, for example n_boot for a number of bootstrap replicates that is smaller in the fake scenarios. A setting column MUST be an atomic vector, and its name MUST be syntactic. It MUST have a value for each fake scenario. It MAY have NA for "real", when only the fake scenarios use the setting. The argsets of "real", its cache key and its manifest$settings then do not hold the setting. A data function MUST NOT take such a setting as an argument: plnr finds no value of it for "real", and run_plan() stops. Its name MUST NOT be one of scenario, sim, analysis, seed, index_analysis, name, fn, fn_name, data and argset. add_analyses() puts the setting of the scenario into each argset.

scenarios() stops on a table that breaks a rule, and on a name in only that is not in the table. The error names the problem.

pbn keeps the value of the last call of scenarios() in this R session, and initialize_project() removes it. add_data() gives it to the plan, and get_data() reads it there before add_analyses().

Value

A data.frame with the columns scenario, sims, output when cfg$scenarios has it, and each setting column. It has one row for each chosen scenario in the order of cfg$scenarios. sims is an integer.

See Also

vignette("pbn"), which builds and runs a small fake project.

Other project setup: create_project(), end_unless_real(), folder(), initialize_project(), new_version(), real_data_is_fake(), rules()

Examples

CFG <- list(
  scenarios = data.frame(
    scenario = c("real", "null"),
    sims = c(1, 3),
    n_boot = c(200, 20)
  )
)
pbn::scenarios(CFG)
pbn::scenarios(CFG, only = "null")

Show the numbers of the manuscript, one block at a time

Description

show_blocks() prints the index of the blocks of the project, and show_block() prints one page of one block. They are for a screen whose numbers leave a server only as a screenshot.

Usage

show_blocks(version = NULL, home = NULL)

show_block(k, page = 1, rows = 35, version = NULL, home = NULL)

Arguments

version

The version, for example "v01". The default NULL is the version of the last initialize_project() in this R session.

home

The project folder. The default NULL is the folder of the last initialize_project() in this R session.

k

The block, by its number in blocks or by its name.

page

The page of the block, a whole number from 1.

rows

The rows of one page, a whole number from 1. The default 35 fits one screenshot.

Details

The project declares the blocks in its functions folder, as one object blocks. It is a named list of blocks, in the order of the manuscript. Each block is a function of results, or a block() with such a function and a formatter. The rule set house_2026_11_26 and the newer sets need a block() for each block. The name of a block is its place in the manuscript, for example "Table 1" or "Results para 1: exclusions". In show_block(), each function gets the real results as read_results() returns them. save_results() also calls each function on simulation 1 of every scenario of the run, and writes the values to ⁠<version>_results/<scenario>/blocks.qs2⁠. So a block MUST work on the results of each fake scenario too. A function returns a data.frame, or a character vector that prints as one line for each element. The function formats the numbers for the manuscript, and show_block() prints the table as the function returns it.

A block() returns numbers, and blocks.qs2 holds that raw value. show_block() and show_blocks() call the formatter of the block on the raw value at each call, and print the formatted value. A formatter that returns a data.table prints as a data.table. A raw value with a formatted number in a label cell, see block(), stops both functions, and the error names the block, the column and the cell.

blocks <- list(
  "Table 1" = function(results) results$table1,
  "Results para 1: exclusions" = function(results) results$exclusions
)

Put blocks in the file ⁠<version>_functions/blocks.R⁠, and nowhere else. pbn leaves that file out of manifest$source_md5, so a change of a block does not make the results stale. The rule blocks_list of check_project() fails a use of a name of that file in the other code, because the run then depends on it.

A block MAY run where the packages of the run script are missing. Examples are the console after initialize_project() and the new R session of check_one_file(). show_block() attaches no package. So a block function MUST name the package of each function that it calls, for example data.table::data.table(). When R does not find a function, the error says so.

The results include the kinds of gitexclude, so a block MAY show rows for each person, for example to find a fault. What a person copies or screenshots from the screen is the responsibility of that person.

Both functions need initialize_project() in this R session, because the blocks come from the functions folder that it sourced. Without it they stop. They read the real results from the disk at each call, with read_results(). So they work in the project folder, and on a server after the file of to_one_file(). They stop where read_results() stops. So they also stop on real results whose manifest$failed_fake_checks names a fake scenario with a failed assertion.

show_blocks() calls each block function once. For each block, it prints the number, the name, the rows and the pages. For a function that stops, it prints the error in the place of the rows, and goes on.

show_block() prints these lines:

  1. the number and the name of the block,

  2. the page, for example ⁠page 2 of 4, rows 36 to 70 of 140⁠,

  3. the version and the date of the real run, for example ⁠v01, run 2026-11-26⁠, or ⁠v01, run an unknown date⁠ when the manifest has no run_date,

  4. the rows of the page,

  5. a warning that names the block and the width of its widest line, only when a printed line of the page is more than 270 characters wide.

So a screenshot shows its version and its run date. The version line comes after the page line, so the first two lines keep their place.

Real results MAY come from fake real data, see fake_real_data of initialize_project(). Then show_block() prints the line ⁠FAKE REAL DATA⁠ between the first two lines. show_blocks() prints it under its first line.

It stops on a block function that stops, and the error names the block. During the call, the option width is 270 and the row names are off. No option of R or of data.table cuts a row or a column, and a wide table wraps its columns. Both functions record the options before a block function runs, and set them back at the end of the call. So an option that a block function sets or adds does not stay.

Value

show_blocks(): invisibly, a data.frame with the columns block, name, rows, pages and error. show_block(): invisibly, the whole value of the block function, or of the formatter for a block().

See Also

vignette("pbn"), section "Running on an air-gapped server".

Other one file: check_one_file(), export_blocks(), to_one_file()


Mark a figure of fake data

Description

stamp_fake() adds a large diagonal label "FAKE DATA" to a ggplot when make_outputs() calls the output function for a fake scenario. Otherwise it returns the figure as it is.

Usage

stamp_fake(q)

Arguments

q

A ggplot, or a patchwork of ggplots.

Details

Call it in the figure code of the output function, before the figure is saved: q <- pbn::stamp_fake(q). For "real" on real data, and outside a call of make_outputs(), it returns q unchanged. For "real" whose manifest has fake_real_data TRUE, it adds the label.

The label is one label over the whole figure, also for a ggplot with facets. stamp_fake() wraps the figure in one element with patchwork::wrap_elements(), and puts the label on it with patchwork::inset_element(). The label has no background, so each panel stays visible. The value is a patchwork, which ggplot2::ggsave() saves as before. Call stamp_fake() last, just before the figure is saved. A + after it applies to the label, and a theme with a background then hides the figure.

It stops when q is not a ggplot or a patchwork, for example a grob or a gtable of gridExtra::arrangeGrob(). Stamp each ggplot before you combine it in such an object.

Value

q, with the label for a fake scenario.

See Also

Other output: copy_outputs(), make_outputs(), panel_numbers(), plot_dag(), plot_path_model(), render_built()

Examples

# Outside make_outputs(), stamp_fake() returns the figure as it is.
if (requireNamespace("ggplot2", quietly = TRUE)) {
  q <- ggplot2::ggplot(data.frame(x = 1:3, y = 1:3), ggplot2::aes(x, y))
  identical(pbn::stamp_fake(q), q)
}

Compute the numbers of a descriptive table

Description

table1() computes the numbers of a descriptive table, per group and for all rows. With a style, it also formats these numbers as text.

Usage

table1(d, by, vars, style = NULL)

Arguments

d

A data.table, or a data.frame.

by

The name of the grouping column in d.

vars

A data.table with the columns var and type. var names a column in d. type is "bin" for a 0/1 variable, "cont" for a numeric variable, or "cat" for a categorical variable. Two text columns are optional. label is the printed label of the variable, and NA gives its name. section names the section that the variable belongs to, and NA or "" gives none.

style

NULL, the name of an installed style, or the path to a style file that ends in .yml. table1_styles() gives the names of the installed styles. With NULL, table1() does no formatting. The section Styles below describes a style file.

Details

The groups are the levels of by, plus "All". The levels are the factor levels when by is a factor, and the sorted unique values otherwise. A row with a missing by counts in "All" only. A level of by that is "All" is an error. A level with no rows has a row in the output with n = 0.

For a "bin" variable:

  • events is the count of 1, and pct is 100 * events / n.

  • p compares the levels of by that have a non-missing value. It comes from the Pearson chi-square test without continuity correction. When any expected count is below 5, it comes from Fisher's exact test.

  • Fisher's exact test first uses the default workspace of stats::fisher.test(). When the test stops with that workspace, it runs again with a workspace of 2e7. When it also stops then, p is NA, test is "fisher_failed", and a warning names the variable. A p of Fisher's exact test is exact, never simulated.

  • test is "chisq", "fisher" or "fisher_failed", and it is the same on every row of the variable. When fewer than two levels have a non-missing value, p and test are NA.

  • A value other than 0, 1 or NA is an error.

For a "cont" variable, mean, sd, median, q1 and q3 hold the numbers of the non-missing values. q1 and q3 are the first and the third quartile. The median and the quartiles are stats::quantile() with type = 7, the default of R. p and test are NA in this version.

A "cat" variable has one row for each level and group. The rows of a level are together, in the order of the groups.

  • The levels are the factor levels when the variable is a factor. Otherwise they are the sorted unique values that are not NA, so a number sorts as a number. level holds each level as text.

  • events is the count of the level, and n is the count of the non-missing values of the group. So pct is 100 * events / n, and the percentages of a group with n above 0 add up to 100.

  • p and test follow the rule of a "bin" variable, with the levels in place of 0 and 1. A level with a count of 0 in each group is not part of the test. When fewer than two levels or fewer than two groups remain, p and test are NA.

  • A variable that has no level, because each value is NA and it is not a factor, has one row per group. Its level, events and pct are NA. With a style it gets no level row, only its heading row and the Missing row that missing.show asks for.

A column that does not apply to the type holds NA.

Value

A data.table with one row per variable and group, in the order of vars, and "All" first. A "cat" variable has one row per level and group. The columns are var, grp, n, missing, mean, sd, events, pct, p, test, level, median, q1 and q3. n counts the non-missing values. pbn 2026.12.3 added the last four columns. The column label follows, which pbn 2026.12.4 added: the label of the variable, or the level of a level row. With a style, the columns row, value_pretty (the cell text) and p_pretty (the text of p) follow. The attribute footnotes then holds the footnotes of the style as a character vector. A style can add rows, as the section Styles says. The other columns of each row of the output without a style stay the same.

Styles

A style formats the numbers of table1() for a journal or a report. A style can only format what table1() computes. It cannot add a test of a "cont" variable.

An installed style is the file ⁠inst/table1/<name>_<YYYY_MM_DD>.yml⁠ of pbn. Its name is the file name without .yml. pbn never edits a released style, so a changed style gets a new date.

A style file is a YAML map of sections. Each field of a section is a map with the keys value and source. source is one string that says where the value comes from. table1() takes any source that is not empty. The source of an installed style MUST cite a reference table or a guideline page, as the subsection on the proof of a style says. table1() checks every field when it reads the file. An unknown field, a missing field, a missing source or a value that the field does not allow stops it. The error names the field and the file. The fields that pbn 2026.12.3 added are optional, so a style file of an earlier pbn stays valid. They are cont.median_digits, the section cat, and the fields missing.row_template and missing.row_pct_digits. pbn 2026.12.4 added the optional fields cat.level_prefix and missing.row_label. In pbn 2026.12.8, cont.mean_digits, cont.sd_digits and missing.template became optional. A style needs each of them only when it uses it, as the list of fields says. An optional field that is present gets the same checks as the other fields.

A template is text with placeholders in braces, such as {events}. A template can hold only the placeholders of its field, in any order, and it can hold none. These are the fields:

  • bin.template: the cell of a "bin" row, over {events}, {n} and {pct}. An example is "{events} ({pct})".

  • bin.pct_digits: the decimals of pct, a whole number from 0 to 10.

  • cont.template: the cell of a "cont" row, over {mean}, {sd}, {median}, {q1} and {q3}. An example is "{median} ({q1}-{q3})". A template that holds {median}, {q1} or {q3} needs cont.median_digits.

  • cont.mean_digits and cont.sd_digits (optional): the decimals of mean and of sd, each a whole number from 0 to 10. A template that holds {mean} needs cont.mean_digits, and one that holds {sd} needs cont.sd_digits.

  • cont.median_digits (optional): the decimals of median, q1 and q3, a whole number from 0 to 10.

  • cat (an optional section): it MUST be present when vars has a "cat" variable. When it is present, it MUST hold the three fields below that are not optional.

  • cat.template: the cell of a level row of a "cat" variable, over {events}, {n} and {pct}, as bin.template.

  • cat.pct_digits: the decimals of pct in a level row, a whole number from 0 to 10.

  • cat.heading_template: the cell of the heading row of a "cat" variable. It holds no placeholder. "" gives an empty cell.

  • cat.level_prefix (optional): the text before the level in the column label of a level row, such as "- ".

  • p.digits: the decimals of p, a whole number from 0 to 10.

  • p.template: the text of p, over {p}. "P ={p}" gives P =0.005, and "{p}" gives the number only.

  • p.lower: null, or a number above 0 and below 1. A p below it gets p.below_template in place of p.template.

  • p.below_template: the text of such a p, over {lower}. With p.lower 0.001, "P <{lower}" gives P <0.001.

  • p.upper: null, or a number above 0 and below 1. A p above it gets p.above_template.

  • p.above_template: the text of such a p, over {upper}. With p.upper 0.999, "P >{upper}" gives P >0.999.

  • thousands.mark: the thousands separator, such as ",". The empty string "" gives no separator.

  • thousands.from: a number above 0. A number gets the separator when its rounded absolute value is thousands.from or more. With 10000, 12347 prints as ⁠12,347⁠ and 9999 prints as 9999.

  • missing.show: never, if_any, always, row_if_any or row_always. With if_any, a cell gets missing.template when missing is above 0. With always, each cell that is not NA gets it. With row_if_any, a variable gets a Missing row when its "All" group has a missing value. With row_always, each variable gets a Missing row. The two row choices need missing.row_template.

  • missing.template (optional): the text that table1() adds to the end of a cell, over {missing}. An example is "; {missing} missing". Only if_any and always use it, and they need it.

  • missing.row_template (optional): the cell of a Missing row, over {missing} and {pct}. An example is "{missing} ({pct}%)". The template "{missing}" gives the missing count only, such as "2".

  • missing.row_pct_digits (optional): the decimals of pct in a Missing row, a whole number from 0 to 10. A Missing row needs it only when missing.row_template holds {pct}.

  • missing.row_label (optional): the column label of a Missing row, such as "Missing". Without it, the label is NA.

  • footnotes: a list, which can be empty. Each item is a map with the keys value and source, and value is the text of one footnote.

p.lower and p.upper print with p.digits decimals, so each MUST have no more decimals than p.digits. p.lower MUST be below p.upper. table1() compares p with the thresholds before it rounds p, so 0.9994 is above 0.999. A p equal to a threshold gets p.template.

A style can add rows, and the column row names the kind of each row:

  • "value": a row of the output without a style. A level row of a "cat" variable has p_pretty NA.

  • "heading": one row for each group before the level rows of a "cat" variable. Its cell is cat.heading_template, and its p_pretty is the P of the variable.

  • "missing": one row for each group after the other rows of a variable, when missing.show asks for it. Its cell gives missing and its percent, and its column pct holds that percent, 100 * missing / (n + missing). The denominator counts every row of the group, missing ones included. Its p_pretty is NA.

  • "section": one row for each group before the rows of the first variable of each section, when vars has the column section. Its grp is the group and its label is the section. Each other column is NA.

The column label of a heading row is the label of the variable. A level row has cat.level_prefix and the level, and a Missing row has missing.row_label.

A heading row and a Missing row keep var, grp, n, missing, p and test of the group. Their level and their other numbers are NA, except pct of a Missing row. A table with no "cat" variable, no Missing row and no section keeps the rows of the output without a style.

table1() rounds each number with formatC(), which rounds as the C function sprintf() does. events, n and missing print with no decimals. The thousands separator applies to every number of a cell. A cell is NA when a number of its template is NA, as for a group with n = 0. p_pretty is NA where p is NA.

The proof of a style

pbn installs a style only with the real published Table 1s that prove it. Beside the file ⁠inst/table1/<name>.yml⁠ is the folder ⁠inst/table1/<name>/⁠. For each reference table k, it holds five files:

  • ⁠reference_<k>.csv⁠: the table as printed. It has one row per printed row and one column per printed column. The header holds the printed column headers, and the first column holds the printed row labels. Each cell is the printed string, and an empty cell is "".

  • ⁠source_<k>.yml⁠: the fields authors, title, journal, year, volume, pages, doi, table and transcribed. authors is a list of maps with the keys family and given. pages is the article number or the pages, and table is the number of the table. transcribed is a map with the keys file, by and date.

  • ⁠fake_<k>.csv⁠: the fake data, one row per fake person. An empty cell or NA is a missing value. The fake data MUST give every printed row and column. They need not give the printed numbers.

  • ⁠vars_<k>.csv⁠: the columns var, type, label, levels and section. The one row of type by names the column of the groups. The other rows, with var, type, label and section, are the argument vars. levels gives the order of the groups, or of the levels of a "cat" variable, separated by |. levels and section can be empty.

  • ⁠layout_<k>.yml⁠: the map of the output onto the printed table. Each item of columns names a printed column, except the first, in order. It has cell: value and a grp, or cell: p. Each item of rows names a printed row, in order. It has the key row and, where it applies, var and level, and no other key. row is value, heading or missing as in the column row of the output. It is section for a section heading, and none for a printed row with no computed counterpart.

The test of pbn runs table1(fake, by, vars, style) for each reference table. It compares each printed cell with the cell of the style, the row labels of the first column included. The headers are not cells. The cell of the style is value_pretty of the group, or p_pretty for cell: p, and NA is "". The label of the style is the column label of the same row of the output. No label comes from the layout or the reference. A printed row of section takes the label of the section row of the output. That row MUST come right before the first row of the next variable of the layout, and the label is "" without it. A row of section has "" in each cell after the label. A row of none has "" in each cell. So each printed cell of it that is not empty MUST be an exception with the rule not_computable.

A label cell, in the first column, passes when the two strings are identical. A value cell passes when the two strings have the same shape. The shape is the string with each number masked:

  • The digits before a decimal point . collapse to one N. A thousands separator between them stays as printed, so ⁠12,347⁠ gives ⁠N,N⁠ and 1234 gives N.

  • Each digit after a decimal point becomes its own N, so the shape keeps the number of decimals.

  • Every other character stays as printed, and an empty cell stays empty.

So ⁠397 (27.0%)⁠ and ⁠5 (2.8%)⁠ share the shape ⁠N (N.N%)⁠, and ⁠57 (76%)⁠ gives ⁠N (N%)⁠. ⁠<0.001⁠ gives ⁠<N.NNN⁠, and P =0.010 gives P =N.NNN. A style controls the format of a cell, and the numbers come from the data.

A cell that differs passes only when the file exceptions.yml of the folder lists it. For a value cell, the two strings of the exception MUST have the shapes of the two strings of the cell. For a label cell, they MUST be the same strings.

exceptions.yml is a map with the one key exceptions, a list. Each item has these fields:

  • reference, row and column: the cell, as reference_1, the number of the printed row after the header, and the printed header.

  • printed and style: the printed string and the string of the style.

  • rule, source and justification: why the two differ. source and justification MUST NOT be empty.

rule is one of these:

  • guideline: the reference departs from the author guidelines, and the style follows them. source names the guideline and its page.

  • other_reference: two references disagree, and the style follows the other one. source cites a cell of the other reference.

  • not_computable: table1() cannot compute the cell, such as a P of a "cont" variable.

  • published_error: the format of the printed cell is wrong, such as a median printed without its value. source gives the evidence. A wrong number in the right format has the shape of the style, so it needs no exception.

  • author_decision: a named person decided the format of the cell, and the style follows the decision. source MUST be a decision, the fourth form of a citation below.

The test fails a style in each of these cases:

  • A cell differs, and exceptions.yml does not list it.

  • The strings of an exception do not match those of its cell, as above.

  • A cell matches, and exceptions.yml lists it. For a value cell, the two shapes are equal.

  • An exception names no cell, or a cell twice.

  • The style has no folder. The folder lacks a file, or it holds a file of another name.

  • The source of a field or of an exception holds "editorial", in any case.

  • The source of a field cites none of the four forms of a citation:

    1. a cell, as ⁠reference_1, row 2, column "P"⁠.

    2. the family name of the first author of a reference, with ⁠Table <n>⁠ of its source.

    3. a guide or a guideline with its page, as ⁠p. 4⁠ or ⁠page 4⁠.

    4. a decision of a named person, as ⁠decision: <Name>, <YYYY-MM-DD>: <reason>⁠.

  • A source starts with ⁠decision:⁠, and it does not have the form of a decision. A decision MUST have a name with a letter, a real date, and a reason of three words or more.

A style that pbn cannot prove is withdrawn. pbn removes its file and keeps its name, so table1() stops with the version that withdrew it and the reason. table1_styles() does not list it. pbn 2026.12.4 withdrew ijoa_brief_report_2026_11_20, because it was not proven against real published tables.

See Also

Other shared helpers: table1_styles()

Examples

d <- data.table::data.table(
  g = rep(c("a", "b"), each = 10),
  smoker = rep(c(1, 0, 0, 1), 5),
  age = 21:40
)
vars <- data.table::data.table(
  var = c("smoker", "age"),
  type = c("bin", "cont")
)
pbn::table1(d, by = "g", vars = vars)

# A style file, written to tempdir()
style <- file.path(tempdir(), "example_2026_12_01.yml")
writeLines(c(
  "bin:",
  "  template: {value: '{events} ({pct})', source: example only}",
  "  pct_digits: {value: 1, source: example only}",
  "cont:",
  "  template: {value: '{mean} ({sd})', source: example only}",
  "  mean_digits: {value: 1, source: example only}",
  "  sd_digits: {value: 1, source: example only}",
  "p:",
  "  digits: {value: 3, source: example only}",
  "  template: {value: 'P ={p}', source: example only}",
  "  lower: {value: 0.001, source: example only}",
  "  below_template: {value: 'P <{lower}', source: example only}",
  "  upper: {value: 0.999, source: example only}",
  "  above_template: {value: 'P >{upper}', source: example only}",
  "thousands:",
  "  mark: {value: ',', source: example only}",
  "  from: {value: 10000, source: example only}",
  "missing:",
  "  show: {value: if_any, source: example only}",
  "  template: {value: '; {missing} missing', source: example only}",
  "footnotes:",
  "  - {value: 'Values are n (percent) or mean (SD).', source: example only}"
), style)
t1 <- pbn::table1(d, by = "g", vars = vars, style = style)
t1[, c("var", "grp", "value_pretty", "p_pretty")]
attr(t1, "footnotes")

List the installed Table 1 styles

Description

table1_styles() gives the names of the Table 1 styles that pbn installs. Give one of these names to the argument style of table1().

Usage

table1_styles()

Value

A character vector of style names, such as "name_2026_12_01", sorted in the C locale. It is character(0) when pbn installs no style. It never holds a withdrawn style.

See Also

Other shared helpers: table1()

Examples

pbn::table1_styles()

Write the run of the real data as one file for a server

Description

to_one_file() writes one R script that runs the scenario "real" of the project on a server without a network. A person pastes the file into R there and runs it from the top to the end.

Usage

to_one_file(...)

Arguments

...

Nothing. A call with an argument stops, and the error names the arguments one_file_home and one_file_folders of initialize_project().

Details

Call initialize_project() first, in the project on this computer, with the paths of the server as one_file_home and one_file_folders. to_one_file() takes the version, the project and the paths from that call. Without the paths, it stops and prints the two arguments to add. It stops when the run script or a file of the functions folder changed after that call. It needs no results. So you MAY generate and read the file before the first full run. The results on the server go to ⁠<one_file_home>/<version>_results/⁠.

The file holds these parts, in this order:

  1. A header with the version of pbn, the date, the project folder and the version. It also gives the md5 of each file in it and the workers.

  2. setwd(home), so that the run script runs in its project folder, as ⁠Rscript <version>_run.R⁠ does.

  3. The run script as it is written, with three changes. Its call of pbn::initialize_project() gets the paths of the server as home and folders, and the argument generated. generated holds the code of each .R file of the functions folder, in the order that org sources them. The call has no one_file_home, one_file_folders, fake_real_data or packages_missing_ok, so the server needs each package. The call pbn::scenarios(CFG) becomes pbn::scenarios(CFG, only = "real"). A line with only a comment such as ⁠# pbn::to_one_file()⁠ is not in the file. The section The md5 of the run script of initialize_project() gives the rule.

  4. A comment that says what to type next, for example pbn::show_blocks().

The section One file of initialize_project() gives the rules of generated. On the server, the run needs no pbn.yml and no functions folder. pbn writes the results and the run log under one_file_home, and, for a data function with cache = TRUE, the cache there too. The manifest holds the md5 of the files of this computer. On this computer, check_one_file() checks that the file gives the real results of the project.

The functions ⁠expect_<scenario>()⁠ of the fake scenarios of CFG$scenarios are not in the file, because the run has the real data only. The comment lines directly above such a function go with it, up to a blank line or a line with code. expect_real() stays. The fake data code stays, because it is inside the data functions.

The run script MAY give fake_real_data = TRUE for this computer. The file never does, because the server holds the real data.

The file is ASCII, because it goes through a clipboard, which can change a byte that is not ASCII. pbn reads each file of the project as UTF-8 and changes each character that is not ASCII on the parse data, token by token. The files of the project stay as they are:

  • In a string, the character becomes its escape, ⁠\uXXXX⁠, or ⁠\UXXXXXXXX⁠ beyond the BMP, for example "\u2265" for the sign greater than or equal. Every other character of the string stays as it is written, also its quotes, its escapes and its line breaks. In a raw string r"(...)", ⁠\u⁠ is text and not an escape. So pbn writes such a raw string again from its value. It becomes a normal string in double quotes on one line, with ⁠\n⁠ for each line break. R does not allow ⁠\u⁠ in a string with an escape ⁠\x⁠ or an octal escape. So pbn writes such a string from its value too. The code of the file is identical() to the code of the project. Such a string gets the encoding mark "UTF-8" where the string of the project MAY have "unknown", and identical() treats the two as equal.

  • In a comment, the character becomes the text ⁠<U+XXXX>⁠.

  • In a name, for example a name in backticks, to_one_file() stops, because R reads a name only as it is written.

to_one_file() stops when, and writes no file:

  • the run script has not exactly one top-level call pbn::initialize_project(), or not exactly one call pbn::scenarios(CFG) with no other argument. It names what it found.

  • a file in the file holds a name that is not ASCII, a NUL, or a line that is not UTF-8. It also stops on a string that is not valid UTF-8 after its escapes. The error names the file and the line.

  • a path of the server or the name of the project folder is not ASCII.

  • code that stays in the file uses a name of an ⁠expect_<scenario>()⁠ that the file leaves out. The file would stop on the server. The error names the file and the line.

  • the assignment of such a function shares a line with other code. That is text before it on its first line, or text other than a comment after it on its last line.

  • the file does not parse.

The file has LF line ends. pbn does not cut long lines, and it prints the length of the longest line. The file keeps the workers of pbn::run_plan() of the run script, and its header says how to change it. The paths go into the file as they are given, without a final / or ⁠\⁠, so give / in a path for Windows too, for example "N:/durable/project".

The file is always ⁠<version>_one_file.R⁠ in the folder of the project of the last initialize_project() of this R session. The printed line names that folder.

These are limits of the file:

  • The comments of the code go into the file as they are written, with ⁠<U+XXXX>⁠ for a character that is not ASCII. So a comment with a path of this computer reaches the server.

  • The rule no_absolute_paths of check_project() does not see a path with one name such as "/data", or a path that paste0() or sprintf() builds. Such a path in the code reaches the server too.

Put the file in git. It is what ran on the server. check_project() knows its name, and its code rules do not read it, because it holds the paths of the server by design.

Value

Invisibly, the path of the file. It prints the path, the number of lines, the size in bytes and the length of the longest line.

See Also

vignette("pbn"), section "Running on an air-gapped server".

Other one file: check_one_file(), export_blocks(), show_blocks()


The formatted string of one block, for the manuscript

Description

txt() returns one string of the formatted value of a block, from the real blocks.qs2 of the version. A manuscript calls it inline, for example `r pbn::txt("Results para 1: effect", version = "v02")`.

Usage

txt(name, row = 1, col = NULL, version = NULL, home = NULL)

Arguments

name

The name of the block in blocks, one string.

row

The row of the formatted value, a whole number from 1.

col

The column of the formatted value when the formatter returns a data.frame: a name or a number. NULL is right only for a character vector or a data.frame with one column.

version

The version, for example "v01". The default NULL is the version of the last initialize_project() in this R session.

home

The project folder. The default NULL is the folder of the last initialize_project() in this R session.

Details

txt() reads the raw value as read_blocks() does: ⁠<home>/<version>_results/real/blocks.qs2⁠ when it exists, which save_results(), update_blocks() and import_blocks() write. In a one-file project without that file, it reads ⁠fake/⁠ with a warning, see the section The folder fake/ of initialize_project(). It formats the value at each call, so a change of a formatter needs no new blocks.qs2.

After initialize_project() of version and home in this R session, txt() takes the block from that session. Else it reads ⁠<version>_functions/blocks.R⁠ without running it. It then needs a call pbn::block() with a string format for the block name, and it evaluates only the function assignments of ⁠<version>_functions/formatters.R⁠. Their parent environment holds the top-level assignments of the other .R files of the functions folder, such as CFG, in the order that initialize_project() sources them. A top-level call that is not an assignment, such as cat(), does not run. The default home is then the working folder. The default version needs initialize_project().

txt() stops when the block, the row, the column or blocks.qs2 is missing. It also stops when the block is not a pbn::block(), or when the cell is not a string. It stops on a raw value that breaks the rule of block().

Value

One string.

See Also

block(), show_block().


Write blocks.qs2 again from the saved results

Description

update_blocks() evaluates the blocks on the saved results of each scenario of the version, and writes blocks.qs2 of each one. It runs no analysis.

Usage

update_blocks(version = NULL, home = NULL)

Arguments

version

The version, for example "v01". The default NULL is the version of the last initialize_project() in this R session.

home

The project folder. The default NULL is the folder of the last initialize_project() in this R session.

Details

It does what step 7 of save_results() does, for each folder ⁠<version>_results/<scenario>/⁠ that holds a results.qs2. In a one-file project, the folder of "real" is ⁠fake/⁠, and update_blocks() does not change ⁠real/⁠, the results of the server. See the section The folder fake/ of initialize_project(). It creates blocks.qs2 where it is absent. Call it after a change of the raw value of a block, or to create the files without a run. A change of a formatter needs no call, because show_block() and txt() format at each call. blocks.qs2 holds the raw value of each block.

It needs initialize_project() of version in this R session. It stops as save_results() does on a block that fails or that breaks the rule of block(). Then it writes no file.

Value

Invisibly, the names of the scenarios that it wrote.

See Also

block(), show_block().


Run a version and check the project

Description

verify() runs ⁠<version>_run.R⁠ in a new R session, and then checks the project with the rules of check_project(). It prints a short verdict: the exit status of the run, each failed assertion of check.csv, and each FAIL and WARN finding.

Usage

verify(version, home = ".")

Arguments

version

The version, "v" and two digits, for example "v01".

home

The project folder. The run script runs with it as the working directory, as ⁠Rscript v01_run.R⁠ does when you start it there.

Details

The new R session is that of callr::rscript(), with the library paths of this session. The output of the run shows as it comes.

verify() reads only the check.csv files of this run. These are the files ⁠<version>_results/<scenario>/check.csv⁠ that changed at or after the start of the run. Before the run starts, verify() waits for the next whole second, up to 1 second, and that second is the start. So a check.csv of an earlier run is older than the start, also on a file system that keeps the time of a change in whole seconds. The failed assertions are the rows of these files with a value of pass that is not TRUE.

The verdict is FAIL when one of these is true:

  • the run ends with a status other than 0.

  • the run wrote no check.csv. Then it checked no fake scenario, for example because it stopped before save_results().

  • a check.csv of the run has a failed assertion. This holds at each level of the rule scenario_checks in pbn.yml, also off.

  • a rule of check_project() fails.

Else the verdict is PASS. The last line names each reason of a FAIL. A PASS of a run that did not write ⁠<version>_results/real/results.qs2⁠, or ⁠<version>_results/fake/results.qs2⁠ in a one-file project, has the last line ⁠Verdict: PASS on the fake scenarios only. The scenario `real` did not run.⁠ It covers the fake data only. Its verdict is still PASS. In a non-interactive R session, verify() quits R with status 1 after a verdict FAIL, as check_project() does.

Value

Invisibly, a list with three elements. status is the exit status of the run. assertions is a data.frame of the failed assertions, with the columns file, assertion, expected and observed. findings holds the findings, as check_project() returns them.

See Also

Other checks: check_project(), freeze_version()

Examples

pbn::verify("v01")