| Title: | Keep Data, R Code, and Outputs Organized and Reproducible |
|---|---|
| Description: | Creates a standardised project skeleton for research projects in R that is loosely inspired by the 'psych-DS' data standard (<https://psych-ds.github.io/>) for psychological data, and checks whether an existing project follows the same conventions. The layout is not fully 'psych-DS' compliant -- most notably the 'dataset_description.json' metadata file is optional rather than required, and can be generated from the 'codebook' files -- hence 'psych-DS-ish'. Single- and multi-study projects are supported. Alongside the directory structure it generates 'Quarto' templates for processing and analysis code (including a 'codebook' for the processed data), a 'README', a licence, a citation file, a '.gitignore' with sensible defaults, and a 'Quarto' project file that renders the code in order. A 'validator' function reports whether a project follows the conventions, including whether raw data have changed since they were first committed to 'Git' and whether rendered reports are up to date, and, where it does not, how to fix it. 'RStudio' users can create projects from the New Project wizard and validate them from the 'Addins' menu. See 'Hussey' (2026) <doi:10.5281/zenodo.21441984> for the archived software record. |
| Authors: | Ian Hussey [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-8906-7559>) |
| Maintainer: | Ian Hussey <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.2.3 |
| Built: | 2026-11-29 19:42:58 UTC |
| Source: | https://github.com/cran/psychdsish |
Recursively finds .qmd and .Rmd files under root, renders each with
unused_dependencies() (which tries Quarto first and falls back to R Markdown),
and returns a single tibble with a file column and the detected
possibly_unused_packages.
check_unused_dependencies(root = ".")check_unused_dependencies(root = ".")
root |
Directory to scan (default "."). |
A tibble with columns:
file (relative path to the document)
possibly_unused_packages (character; one row per package per file)
Files that fail to render are reported via a message and skipped.
# Renders each document, so requires the Quarto command line tools if (!is.null(quarto::quarto_path())) { project <- file.path(tempdir(), "unused_dependencies_demo") dir.create(project) writeLines( c( "---", "title: Demo", "---", "", "```{r}", "library(tools) # attached but never used", "x <- mean(1:10)", "```" ), file.path(project, "analysis.qmd") ) print(check_unused_dependencies(project)) unlink(project, recursive = TRUE) }# Renders each document, so requires the Quarto command line tools if (!is.null(quarto::quarto_path())) { project <- file.path(tempdir(), "unused_dependencies_demo") dir.create(project) writeLines( c( "---", "title: Demo", "---", "", "```{r}", "library(tools) # attached but never used", "x <- mean(1:10)", "```" ), file.path(project, "analysis.qmd") ) print(check_unused_dependencies(project)) unlink(project, recursive = TRUE) }
Recursively searches for R/Quarto files and applies
check_unused_objects_single_file() to each, collating results.
check_unused_objects( root = ".", patterns = c("\\.R$", "\\.r$", "\\.Rmd$", "\\.rmd$", "\\.qmd$", "\\.Qmd$"), exclude_dirs = c(".git", "renv", "_site", "_freeze", ".quarto", "_book", "tools"), verbose = FALSE )check_unused_objects( root = ".", patterns = c("\\.R$", "\\.r$", "\\.Rmd$", "\\.rmd$", "\\.qmd$", "\\.Qmd$"), exclude_dirs = c(".git", "renv", "_site", "_freeze", ".quarto", "_book", "tools"), verbose = FALSE )
root |
Character scalar. Directory to search from (default |
patterns |
Character vector of regexes for file extensions to include. Defaults to common R and Quarto suffixes. |
exclude_dirs |
Character vector of directory names to skip anywhere in
the path (default: |
verbose |
Logical; if |
Supported extensions: .R, .r, .Rmd, .rmd, .qmd, .Qmd.
A data frame with columns:
File path (character).
Name of an object that is created but never used (character).
One row per unused object. If none are found, returns an empty data frame with the two columns.
project <- file.path(tempdir(), "unused_objects_demo") dir.create(project) writeLines( c( "df1 <- data.frame(x = 1:3)", "df2 <- transform(df1, y = x * 2) # never used", "print(df1)" ), file.path(project, "analysis.R") ) check_unused_objects(project) unlink(project, recursive = TRUE)project <- file.path(tempdir(), "unused_objects_demo") dir.create(project) writeLines( c( "df1 <- data.frame(x = 1:3)", "df2 <- transform(df1, y = x * 2) # never used", "print(df1)" ), file.path(project, "analysis.R") ) check_unused_objects(project) unlink(project, recursive = TRUE)
Parses an R script or an R/Quarto document, extracts the R code, and reports
symbols that are assigned to but never referenced anywhere else in the same file.
Supports .R, .Rmd, and .qmd (R code chunks only for the latter two).
check_unused_objects_single_file(path)check_unused_objects_single_file(path)
path |
Character. Path to a file. |
A data frame with one column, unused_objects, listing orphaned objects.
Returns an empty data frame if no orphans are found.
path <- tempfile(fileext = ".R") writeLines( c( "df1 <- data.frame(x = 1:3)", "df2 <- transform(df1, y = x * 2) # never used", "print(df1)" ), path ) check_unused_objects_single_file(path) unlink(path)path <- tempfile(fileext = ".R") writeLines( c( "df1 <- data.frame(x = 1:3)", "df2 <- transform(df1, y = x * 2) # never used", "print(df1)" ), path ) check_unused_objects_single_file(path) unlink(path)
This function creates a standardised-ish directory and file structure for a
research project. The layout is loosely inspired by the
psych-DS specification, but is not
fully psych-DS compliant. It adds extra conventions for reproducibility
and common analysis workflows, including Quarto file templates and
a .gitignore file. It does not comply with psych-ds's .json requirement.
create_project_skeleton( project_root, overwrite = FALSE, rproj = TRUE, quarto_yml = TRUE, studies = 1, layout = c("by_study", "by_type"), quiet = FALSE )create_project_skeleton( project_root, overwrite = FALSE, rproj = TRUE, quarto_yml = TRUE, studies = 1, layout = c("by_study", "by_type"), quiet = FALSE )
project_root |
Character scalar. Path to the root directory where
the project skeleton should be created, e.g., |
overwrite |
Logical. If |
rproj |
Logical. If |
quarto_yml |
Logical. If |
studies |
Whole number. The number of studies in the project.
Defaults to |
layout |
Character. How a multi-study project is arranged (ignored if
In both layouts, |
quiet |
Logical. If |
The created structure is designed to separate raw data, processed data, analysis code, outputs, and documentation, while including sensible defaults for licensing, reproducibility, and version control.
The following directories are created (if not already present):
code/ - analysis and processing scripts (.qmd/.Rmd)
reports/ - manuscripts, slides, preprints, etc.
data/
data/raw/ - immutable raw data + dictionaries/codebooks
data/processed/ - cleaned datasets and dictionaries
data/outputs/ - outputs from processing/analysis scripts
plots/ - figures (.png, .pdf, etc.)
fitted_models/ - saved model objects (e.g., .rds)
results/ - tables, summaries, descriptive statistics
methods/ - measurement instruments, implementation files
preregistration/ - preregistration documents
tools/ - utility scripts and reproducibility helpers
Directories that would otherwise be empty receive an empty .gitkeep file
so that they are tracked by Git.
The following files are created (if not already present):
LICENSE - CC BY 4.0 license text
README.md - skeleton README describing project aims and structure
<project_name>.Rproj - RStudio project file that does not save or
restore the workspace (if rproj = TRUE)
_quarto.yml - Quarto project file listing the .qmd files to
render, in order, when the whole project is rendered (processing
before analysis) (if quarto_yml = TRUE)
CITATION.cff - citation metadata template; GitHub uses it to show
a "Cite this repository" button
.gitignore - ignores R history, session data, caches, temp files,
OS-specific clutter, and large output directories
code/analysis.qmd - Quarto analysis template with metadata, setup
chunk, and sessionInfo() chunk
code/processing.qmd - Quarto processing template (same structure)
tools/project_creator.qmd - re-runs create_project_skeleton()
from within the project, with an optional (not evaluated by default)
chunk calling delete_project_skeleton() for testing
tools/project_validator.qmd - runs validator() on the project
tools/style_all_files.qmd - reproducibility tool to apply
tidyverse code style to all .qmd, .Rmd, and .R files
Quarto .qmd files are pre-filled with:
YAML front matter including title, author, date, HTML output settings
Global options to suppress scientific notation, warnings, and messages
Setup chunk for loading packages and configuring the session
Session information chunk
(Invisibly) a data.frame with one row per directory or file the function
handled, containing:
Path relative to project_root.
Either "dir" or "file".
"created" if it did not exist, "overwritten" if it
existed and overwrite = TRUE, "skipped" if a file existed and
overwrite = FALSE, or "exists" if a directory already existed.
# These examples write to a temporary folder; use your project's path instead, # e.g., create_project_skeleton("~/git/my_project") project <- file.path(tempdir(), "my_project") create_project_skeleton(project) list.files(project, all.files = TRUE) # Running it again skips existing files, unless overwrite = TRUE create_project_skeleton(project) # A project with two studies, one folder per study (study_1/code/, ...) two_studies <- file.path(tempdir(), "two_studies") create_project_skeleton(two_studies, studies = 2) # The same, with one subfolder per study inside each folder (code/study_1/, ...) by_type <- file.path(tempdir(), "two_studies_by_type") create_project_skeleton(by_type, studies = 2, layout = "by_type") unlink(c(project, two_studies, by_type), recursive = TRUE)# These examples write to a temporary folder; use your project's path instead, # e.g., create_project_skeleton("~/git/my_project") project <- file.path(tempdir(), "my_project") create_project_skeleton(project) list.files(project, all.files = TRUE) # Running it again skips existing files, unless overwrite = TRUE create_project_skeleton(project) # A project with two studies, one folder per study (study_1/code/, ...) two_studies <- file.path(tempdir(), "two_studies") create_project_skeleton(two_studies, studies = 2) # The same, with one subfolder per study inside each folder (code/study_1/, ...) by_type <- file.path(tempdir(), "two_studies_by_type") create_project_skeleton(by_type, studies = 2, layout = "by_type") unlink(c(project, two_studies, by_type), recursive = TRUE)
This function deletes the contents of a project folder, but protects the file from which it is being executed (and the minimal set of ancestor directories required to keep that file). It is intended for cleaning out automatically generated project skeletons while leaving the active script or Quarto/Rmd file intact.
delete_project_skeleton( project_root, require_sentinel = TRUE, sentinel_names = c(".ok-to-prune", ".git", ".gitignore", ".here", "_project.yml", "_quarto.yml"), confirm = TRUE, dry_run = FALSE, large_n_warn = 10000, keep_file = NULL )delete_project_skeleton( project_root, require_sentinel = TRUE, sentinel_names = c(".ok-to-prune", ".git", ".gitignore", ".here", "_project.yml", "_quarto.yml"), confirm = TRUE, dry_run = FALSE, large_n_warn = 10000, keep_file = NULL )
project_root |
Path to the project folder whose contents should
be deleted, e.g., |
require_sentinel |
Logical. If |
sentinel_names |
Character vector of sentinel filenames checked
when |
confirm |
Logical. If |
dry_run |
Logical. If |
large_n_warn |
Integer. Threshold number of items that triggers
an additional confirmation prompt. Default is |
keep_file |
Path to the file to protect, or |
Several safety mechanisms are built in to reduce the risk of catastrophic deletion:
Refuses to operate on filesystem roots (e.g., / or C:/).
Optionally requires a sentinel file (e.g., .ok-to-prune)
or other project marker in the target directory.
Displays an interactive confirmation prompt requiring the exact folder name to be typed.
Aborts in non-interactive sessions unless confirm = FALSE
is set explicitly.
Supports a dry-run mode to preview deletions.
Issues an extra confirmation if the number of items to be deleted is very large.
As an additional safeguard, unless keep_file is supplied, the function
must be able to identify the file it is being called from (via
knitr/Quarto, RStudio, or Rscript --file=) so that it never deletes the
running script or its parent directories. It is therefore intended to be
run from a script such as tools/project_creator.qmd, and it aborts if the
current file cannot be determined.
A dry run (dry_run = TRUE) does not ask for confirmation, because it
deletes nothing.
Invisibly, a list with project_root, keep_file, paths (the
top-level paths deleted, or that would be deleted if dry_run = TRUE,
relative to project_root), and n_items (the number of files and
directories they contain, including themselves).
Deletion is irreversible. Always test with dry_run = TRUE first, and
keep require_sentinel = TRUE and confirm = TRUE for normal use.
project <- file.path(tempdir(), "my_project") create_project_skeleton(project, quiet = TRUE) keep <- file.path(project, "tools", "project_creator.qmd") # Preview what would be deleted delete_project_skeleton(project, keep_file = keep, dry_run = TRUE) # Delete everything except `keep`. confirm = FALSE skips the typed # confirmation: only use it when you are sure. delete_project_skeleton(project, keep_file = keep, confirm = FALSE) list.files(project, recursive = TRUE) # From a script inside the project (e.g., tools/project_creator.qmd), the # running file is detected and protected, so `keep_file` is not needed: # delete_project_skeleton(project_root = "../") unlink(project, recursive = TRUE)project <- file.path(tempdir(), "my_project") create_project_skeleton(project, quiet = TRUE) keep <- file.path(project, "tools", "project_creator.qmd") # Preview what would be deleted delete_project_skeleton(project, keep_file = keep, dry_run = TRUE) # Delete everything except `keep`. confirm = FALSE skips the typed # confirmation: only use it when you are sure. delete_project_skeleton(project, keep_file = keep, confirm = FALSE) list.files(project, recursive = TRUE) # From a script inside the project (e.g., tools/project_creator.qmd), the # running file is detected and protected, so `keep_file` is not needed: # delete_project_skeleton(project_root = "../") unlink(project, recursive = TRUE)
Returns a long chunk of R/tidyverse code that has intentionally
inconsistent formatting, spacing, and indentation. It is designed for use in
demonstrations of code style tools such as styler::style_text() or
styler::style_file().
poorly_styled_code()poorly_styled_code()
The code:
Loads dplyr, ggplot2, and stringr.
Performs grouping, summarisation, filtering, joining, and plotting on
the built-in mtcars dataset.
Is deliberately badly formatted (inconsistent spacing, misaligned pipes, poor indentation, inconsistent line breaks).
The output is meant to provide an example input for automatic code formatting tools, so that users can compare the before (poor style) and after (styled) versions. The code is only returned, never run.
A character vector of class psychdsish_code, with one element per line of
code. Printing it shows the code in the console; it can be passed directly
to styler::style_text() or written to a file with writeLines().
styler::style_text(), styler::style_file()
# Show the messy code code <- poorly_styled_code() code # Pass it to styler to see how formatting improves styler::style_text(code)# Show the messy code code <- poorly_styled_code() code # Pass it to styler to see how formatting improves styler::style_text(code)
Recursively finds .R, .Rmd, and .qmd files under a directory and
restyles them using styler::style_file(). This includes both code scripts
and R code chunks embedded in R Markdown or Quarto documents. Certain
directories can be excluded from the search.
style_all_files( root, patterns = c("\\.R$", "\\.r$", "\\.Rmd$", "\\.rmd$", "\\.qmd$", "\\.Qmd$"), exclude_dirs = c(".git", "renv", "_site", "_freeze", ".quarto", "_book", "tools"), dry_run = FALSE, ... )style_all_files( root, patterns = c("\\.R$", "\\.r$", "\\.Rmd$", "\\.rmd$", "\\.qmd$", "\\.Qmd$"), exclude_dirs = c(".git", "renv", "_site", "_freeze", ".quarto", "_book", "tools"), dry_run = FALSE, ... )
root |
Character scalar. Path to the root directory to search. There
is no default, because the files found are rewritten: from
|
patterns |
Character vector of regular expressions for file extensions to include. Defaults to common R and Quarto file suffixes. |
exclude_dirs |
Character vector of directory names to skip (default:
|
dry_run |
Logical. If |
... |
Additional arguments passed on to |
The search is recursive, starting at root.
Excluded directories are filtered out using a regex match anywhere in the path.
If no matching files are found, a message is issued and an empty character vector is returned invisibly.
Invisibly returns the vector of file paths that were styled.
If dry_run = TRUE, returns the vector of candidate file paths without
styling.
styler::style_file(), styler::style_dir(), usethis::use_tidy_style()
project <- file.path(tempdir(), "style_demo") dir.create(project) writeLines("x<-c(1,2 ,3)", file.path(project, "messy.R")) # Preview which files would be styled style_all_files(project, dry_run = TRUE) # Style them style_all_files(project) readLines(file.path(project, "messy.R")) unlink(project, recursive = TRUE)project <- file.path(tempdir(), "style_demo") dir.create(project) writeLines("x<-c(1,2 ,3)", file.path(project, "messy.R")) # Preview which files would be styled style_all_files(project, dry_run = TRUE) # Style them style_all_files(project) readLines(file.path(project, "messy.R")) unlink(project, recursive = TRUE)
This function checks whether a project directory follows a defined set
of structural and file-placement rules. The layout is loosely inspired by the
psych-DS specification, but is not
fully psych-DS compliant. It adds extra conventions for reproducibility
and common analysis workflows, including Quarto file templates and
a .gitignore file. It does not comply with psych-ds's .json requirement.
validator( project_root = "../", exclude_dirs = c("renv", "packrat", "_site", "_book", "_freeze", "node_modules"), strict = FALSE )validator( project_root = "../", exclude_dirs = c("renv", "packrat", "_site", "_book", "_freeze", "node_modules"), strict = FALSE )
project_root |
Character scalar. Path to the project root directory.
Defaults to |
exclude_dirs |
Character vector of directory names whose contents are
ignored, in addition to all hidden directories (those whose name starts
with a dot, e.g., |
strict |
Logical. If |
The project's layout is detected from its folders: multi-study "by study"
if there are study_1/, study_2/, etc. folders at the project root,
multi-study "by type" if there are such folders inside code/,
data/raw/, etc., and single-study otherwise (see
create_project_skeleton()). The checks below are applied to each study's
folders. In multi-study projects, .qmd, .Rmd, and .R files for
analyses that combine studies may also be placed in a root-level code/
folder (by study) or anywhere in code/ (by type).
The validator performs several categories of checks:
Required directories — Ensures that expected top-level and
nested folders exist (e.g., code/, data/raw/, methods/).
Required files — Confirms presence of a readme.md and
a license file (e.g., LICENSE).
Filetype-location constraints — Ensures specific file types
(e.g., .qmd, .csv, .rds, .png) only appear in approved
subdirectories and not elsewhere in the project.
Special HTML rule — All .html files must be under code/
or methods/.
Hygiene checks — Optional rules that discourage spaces in
filenames, check for .gitignore presence, and prevent data
files being stored under code/.
Reproducibility checks — Raw data files have not been modified
or deleted since they were first committed to git (including
uncommitted changes); rendered .html files are newer than their
.qmd (using git commit times for committed, unmodified files, and
file modification times otherwise); README.md no longer contains
the template placeholders written by create_project_skeleton();
and R code in .R files and in .qmd/.Rmd code chunks contains
no setwd() calls or absolute file paths (e.g., "~/",
"/Users/", "C:/"). Comment lines are ignored.
Codebook checks — Every data file under data/ is documented,
by a codebook named after it (e.g.,
study-1_stage-processed_data.csv ->
study-1_stage-processed_codebook.csv, any data file extension),
a psych-DS sidecar (study-1_stage-processed_data.json), or its
columns being listed in dataset_description.json. .csv/.tsv
codebooks no longer contain the "TO BE COMPLETED MANUALLY"
placeholders written by the codebook chunk in
code/processing.qmd. Undocumented raw data is a warning rather
than a failure.
psych-DS checks (reported as "WARN") — Data file names follow
the psych-DS convention of key-value pairs ending in _data
(leniently for raw data, which often cannot be renamed); data files
are described in dataset_description.json rather than only in a
.csv/.xlsx codebook (see write_dataset_description()); and
every codebook or .json under data/ can be matched to the data
file it describes.
Checks that cannot be run are reported as "SKIP" rather than "PASS",
e.g., the raw data check when the project is not a git repository, or the
.html check when nothing has been rendered yet. Checks that are worth
acting on but are not failures, such as a project that works but is not
fully psych-DS compliant, are reported as "WARN". Neither causes
strict = TRUE to fail.
A tibble of class psychdsish_validation with one row per check
(failures first, then warnings and skipped checks), containing:
Description of the check performed.
"PASS", "FAIL", "WARN" (worth fixing, but not a
failure), or "SKIP" (the check could not be run).
Additional information, such as instructions for fixing failures or offending file paths.
Printing it shows coloured PASS/FAIL results with guidance for failures.
summary() returns a list with project_root, layout ("single",
"by_study", or "by_type"), studies (the study folder names),
n_pass, n_fail, n_warn, n_skip, and passed (TRUE if no check
failed). If strict = TRUE and any check
fails, an error is thrown instead.
project <- file.path(tempdir(), "my_project") create_project_skeleton(project, quiet = TRUE) # Validate the project and print the results results <- validator(project) results # Overall result summary(results)$passed # Throw an error if any check fails, e.g., to fail a GitHub Actions job try(validator(project, strict = TRUE)) # Display the results as a table, e.g., in a Quarto report if (requireNamespace("knitr", quietly = TRUE)) { knitr::kable(results) } unlink(project, recursive = TRUE)project <- file.path(tempdir(), "my_project") create_project_skeleton(project, quiet = TRUE) # Validate the project and print the results results <- validator(project) results # Overall result summary(results)$passed # Throw an error if any check fails, e.g., to fail a GitHub Actions job try(validator(project, strict = TRUE)) # Display the results as a table, e.g., in a Quarto report if (requireNamespace("knitr", quietly = TRUE)) { knitr::kable(results) } unlink(project, recursive = TRUE)
Creates or updates dataset_description.json in the project root, which
the psych-DS standard requires. The
variables it describes are taken from the codebooks created by the codebook
chunk in code/processing.qmd, so that each variable is described once, in
the codebook, rather than twice.
write_dataset_description( project_root, name = NULL, description = NULL, quiet = FALSE )write_dataset_description( project_root, name = NULL, description = NULL, quiet = FALSE )
project_root |
Character scalar. Path to the project root, e.g.,
|
name |
Character scalar. The dataset's name. Defaults to the name in
an existing |
description |
Character scalar. A description of the dataset. Defaults to the description in an existing file, or a placeholder to complete by hand. |
quiet |
Logical. If |
Documenting variables in a codebook .csv is the simpler option, and is
all that validator() requires. Writing them to
dataset_description.json as well is more work, but makes the project
closer to a valid psych-DS dataset, which is machine-readable and easier
for others to reuse. Use whichever suits the project; you do not need both.
Each codebook row becomes a PropertyValue entry in variableMeasured,
mapping the codebook's variable, description, and units columns onto
name, description, and unitText. A coding entry that is not
"none" is appended to the description, because psych-DS has no separate
field for it. Where the same variable appears in more than one codebook,
the first description is used.
Fields that the file already contains and that this function does not
write (e.g., author or license) are kept.
Data file names in the templates follow the psych-DS convention of
key-value pairs ending in _data, e.g.,
study-1_stage-processed_data.csv. To check a project against the
standard itself, use the psych-DS validator
(https://psych-ds.github.io/validator/).
(Invisibly) a list with path, name, description, and variables
(the variable names written).
create_project_skeleton(), validator()
project <- file.path(tempdir(), "psychds_project") create_project_skeleton(project, quiet = TRUE) # normally written by the codebook chunk in code/processing.qmd write.csv( data.frame( variable = c("id", "rt"), description = c("Participant identifier", "Response time"), units = c("none", "milliseconds"), coding = c("none", "none") ), file.path(project, "data", "processed", "stage-processed_codebook.csv"), row.names = FALSE ) write_dataset_description(project, name = "My study", description = "A demo") cat(readLines(file.path(project, "dataset_description.json")), sep = "\n") unlink(project, recursive = TRUE)project <- file.path(tempdir(), "psychds_project") create_project_skeleton(project, quiet = TRUE) # normally written by the codebook chunk in code/processing.qmd write.csv( data.frame( variable = c("id", "rt"), description = c("Participant identifier", "Response time"), units = c("none", "milliseconds"), coding = c("none", "none") ), file.path(project, "data", "processed", "stage-processed_codebook.csv"), row.names = FALSE ) write_dataset_description(project, name = "My study", description = "A demo") cat(readLines(file.path(project, "dataset_description.json")), sep = "\n") unlink(project, recursive = TRUE)