Type: | Package |
Title: | Base Tools for Semi-Automatic Reporting of Ordinary Surveys |
Version: | 1.1.0 |
Maintainer: | Stephan Daus <stephus.daus@gmail.com> |
Description: | Scaffold an entire web-based report using template chunks, based on a small chapter overview and a dataset. Highly adaptable with prefixes, suffixes, translations, etc. Also contains tools for password-protecting, e.g. for each organization's report on a website. Developed for the common case of a survey across multiple organizations/sites where each organization wants to obtain results for their organization compared with everyone else. See 'saros' (https://CRAN.R-project.org/package=saros) for tools used for authors in the drafted reports. |
Note: | Free to use for non-Norwegian institutions, otherwise see LICENSE. |
License: | MIT + file LICENSE |
URL: | https://nifu-no.github.io/saros.base/, https://github.com/NIFU-NO/saros.base |
BugReports: | https://github.com/NIFU-NO/saros.base/issues |
Depends: | R (≥ 4.2.0) |
Imports: | utils, vctrs, rlang, cli, tidyselect, dplyr, tidyr, glue, stringi, forcats, fs, yaml, zip, rstudioapi, bcrypt |
Suggests: | covr, haven, srvyr, readr, qs, purrr, writexl, webshot, usethis, quarto, labelled, testthat (≥ 3.0.0), tibble, withr, spelling |
SystemRequirements: | None. |
Config/testthat/edition: | 3 |
Encoding: | UTF-8 |
LazyData: | true |
RoxygenNote: | 7.3.2 |
Language: | en-US |
VignetteBuilder: | quarto |
Config/Needs/website: | rmarkdown |
Config/testthat/parallel: | true |
NeedsCompilation: | no |
Packaged: | 2025-05-31 17:19:36 UTC; py128 |
Author: | Stephan Daus |
Repository: | CRAN |
Date/Publication: | 2025-06-01 10:10:02 UTC |
Add Sample Size Range to Chapter Structure
Description
Takes chapter_structure
and data
and returns the chapter_structure
with
an attached variable containing a string with the sample size-range (or
single value if min=max). Allows specifying the glue_template_1 (single value)
and glue_template_2 (for min and max values).
Usage
add_n_range_to_chapter_structure(
chapter_structure,
data,
glue_template_1 = "{n}",
glue_template_2 = "[{n[1]}-{n[2]}]",
variable_name = ".n_range"
)
Arguments
chapter_structure |
A grouped tibble. If not grouped, will give a warning and continue with rowwise processing, which is unlikely what you want. |
data |
The raw data, with matching column names as in
|
glue_template_1 , glue_template_2 |
Glue templates. |
variable_name |
String, name of new variable to attach. Defaults to ".n_range" |
Value
chapter_structure with a new variable added. Grouped as before.
Convenience Function to Copy Only the Contents of A Folder to Another Folder
Description
Convenience Function to Copy Only the Contents of A Folder to Another Folder
Usage
copy_folder_contents_to_dir(
from,
to,
overwrite = FALSE,
only_copy_folders = FALSE
)
Arguments
to , from |
String, path from where to copy the contents, and where to copy them to. |
overwrite |
Flag. Defaults to FALSE. |
only_copy_folders |
Flag. Defaults to FALSE. If TRUE, only copies folders. |
Value
No return value, called for side effects
Examples
copy_folder_contents_to_dir(
from = system.file("help", "figures", package = "dplyr"),
to = tempdir()
)
Create a Pre-defined Directory Hierarchy on Disk
Description
Create a Pre-defined Directory Hierarchy on Disk
Usage
create_directory_structure(
path,
structure_path = system.file("templates", "_project_structure_en.yaml", package =
"saros.base"),
numbering_prefix = c("none", "max_local", "max_global"),
numbering_inheritance = TRUE,
word_separator = NULL,
numbering_parent_child_separator = word_separator,
numbering_name_separator = " ",
case = c("asis", "sentence", "title", "lower", "upper", "snake"),
replacement_list = c(project_initials = "SSN"),
create = FALSE,
count_existing_folders = FALSE
)
Arguments
path |
String, path to where to create the project files |
structure_path |
String. Path to the YAML file that defines the folder structure. Defaults to system.file("templates", "_project_structure_en.yaml"). |
numbering_prefix |
String. One of c("none", "max_local", "max_global"). |
numbering_inheritance |
Flag. Whether to inherit numbering from parent folder. |
word_separator |
String. Replace separators between words in folder names. Defaults to NULL. |
numbering_parent_child_separator |
String. Defaults to word_separator. |
numbering_name_separator |
String. Separator between numbering part and name. |
case |
String. One of c("asis", "sentence", "lower", "upper", "title", "snake"). |
replacement_list |
named character vector. Each name in this vector will be replaced with its |
create |
Boolean. Defaults to TRUE in initialize_saros_project(), FALSE in create_directory_structure(). |
count_existing_folders |
Boolean. Defaults to FALSE. |
Value
No return value, called for side effects
Examples
struct <- create_directory_structure(path = tempdir(), create = FALSE)
Create Data Frame Containing Email Drafts with User Credentials
Description
Create Data Frame Containing Email Drafts with User Credentials
Usage
create_email_credentials(
email_data_frame,
email_col = "email",
username_col = "username",
local_main_password_path = ".htpasswd_private",
ignore_missing_emails = FALSE,
email_body = "Login credentials are \nUsername: {username},\nPassword: {password}",
email_subject = "User credentials for website example.net.",
...
)
Arguments
email_data_frame |
Data.frame/tibble with (at least) emails and usernames |
email_col |
String, name of email column |
username_col |
String, name of username column in email_data_frame |
local_main_password_path |
Path to a local .htpasswd file containing username:password header and : as separator. |
ignore_missing_emails |
Flag, defaults to FALSE. Whether usernames existing in password file but not email file will result in warnings. |
email_body , email_subject |
String, subject line and email body respectively. Supports glue syntax referring to columns found in the email data frame or password file. |
... |
Dynamic dots forwarded to quarto::quarto_render |
Value
Data.frame
Create Folder with Placeholder R-files Based on Structure in CSV-file
Description
Create Folder with Placeholder R-files Based on Structure in CSV-file
Usage
create_r_files(
r_files_out_path,
r_files_source_path = system.file("templates", "r_files.csv", package = "saros.base"),
r_optionals = TRUE,
r_add_file_scope = TRUE,
r_prefix_file_scope = "### ",
r_add_folder_scope_as_README = FALSE,
word_separator = NULL,
case = c("asis", "sentence", "title", "lower", "upper", "snake"),
numbering_prefix = c("none", "max_local", "max_global"),
numbering_inheritance = TRUE,
numbering_parent_child_separator = word_separator,
numbering_name_separator = " "
)
Arguments
r_files_out_path |
String, path to where to place R placeholder files. If NULL, will not create any. |
r_files_source_path |
String, path to where to find CSV-field containing the columns folder_name, folder_scope, file_name, file_scope. If NULL, defaults to system.file("templates", "r_files.csv")). |
r_optionals |
Flag. Whether to add files marked as 1 (or TRUE) in the optional column. Defaults to TRUE. |
r_add_file_scope |
Flag. Whether to add value from column 'file_scope' to beginning of each file. Default to TRUE. |
r_prefix_file_scope |
String to add before file_scope. Defaults to "### " |
r_add_folder_scope_as_README |
Flag. Whether to create README file in each folder with the folder_scope column cell in r_files_source_path. Defaults to FALSE. |
word_separator |
String. Replace separators between words in folder names. Defaults to NULL. |
case |
String. One of c("asis", "sentence", "lower", "upper", "title", "snake"). |
numbering_prefix |
String. One of c("none", "max_local", "max_global"). |
numbering_inheritance |
Flag. Whether to inherit numbering from parent folder. |
numbering_parent_child_separator |
String. Defaults to word_separator. |
numbering_name_separator |
String. Separator between numbering part and name. |
Value
No return value, called for side effects
Examples
create_r_files(r_files_out_path = tempdir())
Wrapper to Download and Unzip a Github Repository to A Folder
Description
Wrapper to Download and Unzip a Github Repository to A Folder
Usage
download_zip_to_folder(
github_zip_url = "https://github.com/NIFU-NO/nifutemplates/archive/refs/heads/main.zip",
zip_path = tempfile(fileext = ".zip"),
files = NULL,
out_path,
prompt = TRUE,
overwrite = FALSE,
open_project = FALSE,
newSession = TRUE
)
Arguments
github_zip_url |
URL to zip file, as string. |
zip_path |
String, where to store zip-file. Defaults to a temporary location. |
files |
Character vector of files in zip-file to include. See |
out_path |
String, directory to where to store the unzipped files. |
prompt |
Flag, whether to ask user if conflicting files should be overwritten, if any. Defaults to TRUE. |
overwrite |
Flag, whether to overwrite files in out_path. Defaults to FALSE. |
open_project |
Flag or string. If FALSE (default), does nothing. If TRUE (requires |
newSession |
Flag. Whether to open new project in a new RStudio session. Defaults to TRUE. |
Value
Character vector of unzipped files.
Examples
download_zip_to_folder(
github_zip_url = "https://github.com/NIFU-NO/nifutemplates/archive/refs/heads/main.zip",
out_path = tempdir(), overwrite = TRUE
)
Automatically Draft a Quarto Report
Description
The draft_report()
function takes a raw dataset (data
-argument) and the
output from the refine_chapter_overview()
-function as the
chapter_structure
-argument and outputs a set of pre-populated qmd-files in the
specified path
-folder. You can edit, render, and
ultimately publish these as usual with Quarto features in RStudio. See also
{saros.post}
-package for post-processing tools.
Usage
draft_report(
data,
chapter_structure,
...,
path = tempdir(),
title = NULL,
authors = NULL,
authors_col = "author",
chapter_yaml_file = NULL,
chapter_qmd_start_section_filepath = NULL,
chapter_qmd_end_section_filepath = NULL,
index_filename = "index",
index_yaml_file = NULL,
index_qmd_start_section_filepath = NULL,
index_qmd_end_section_filepath = NULL,
report_filename = "report",
report_yaml_file = NULL,
report_qmd_start_section_filepath = NULL,
report_qmd_end_section_filepath = NULL,
report_includes_files = FALSE,
ignore_heading_for_group = c(".template_name", ".variable_type_dep",
".variable_type_indep", ".variable_group_dep", "chapter"),
replace_heading_for_group = c(.variable_label_suffix_dep = ".variable_name_dep",
.variable_label_suffix_indep = ".variable_name_indep"),
prefix_heading_for_group = NULL,
suffix_heading_for_group = NULL,
require_common_categories = TRUE,
combined_report = TRUE,
write_qmd = TRUE,
attach_chapter_dataset = TRUE,
auxiliary_variables = NULL,
serialized_format = c("rds", "qs"),
max_path_warning_threshold = 260,
filename_prefix = "",
data_filename_prefix = "data_",
report_includes_prefix = "{{< include \"",
report_includes_suffix = "\" >}}",
log_file = NULL
)
Arguments
data |
Survey data
A data frame (or a srvyr-object) with the columns specified in the chapter_structure 'dep', etc columns. |
chapter_structure |
What goes into each chapter and sub-chapter
Data frame (or tibble, possibly grouped). One row per chapter. Should contain the columns 'chapter' and 'dep', Optionally 'indep' (independent variables) and other informative columns as needed. |
... |
Dynamic dots Arguments forwarded to the corresponding functions that create the elements. |
path |
Output path
Path to save all output. Defaults to a temporary directory. |
title |
Title of report
Added automatically to YAML-header of index.qmd and report.qmd-files. |
authors |
Authors of entire report
If NULL, infers from |
authors_col |
Column name for author
Only used if it exists. Multiple authors are separated by semicolon (and optionally with a subsequent space). |
chapter_yaml_file |
Path to YAML-file to insert into each chapter qmd-file
Path to file used to insert header YAML, in each chapter. |
chapter_qmd_start_section_filepath , chapter_qmd_end_section_filepath , index_qmd_start_section_filepath , index_qmd_end_section_filepath , report_qmd_start_section_filepath , report_qmd_end_section_filepath |
Path to qmd-bit for start/end of each qmd
Path to qmd-snippet placed before/after body of all chapter/index/report qmd-files. |
index_filename |
Index filename
The name of the main index Quarto file used as landing page for each report. Will link to a PDF (report.qmd) which collects all chapters. |
index_yaml_file , report_yaml_file |
Path to YAML-file to insert into index.qmd and report.qmd respectively
Path to file used to insert header YAML, in index and report files. |
report_filename |
Report filename
The name of the main report QMD-file used when compiling a complete report
collecting all chapters in its folder (except itself).
If provided, will be linked to in the index.
If NULL, will generate a filename based on the report title, prefixed with "0_".
To turn off, set |
report_includes_files |
Whether report.qmd includes {{< include 'chapter.qmd' >}}
Useful to have in mesos reports. However, bear in mind that including other qmd files with conflicting YAML-headers might be risky. |
ignore_heading_for_group |
Ignore heading for group
Type of refined chapter_structure data for which to suppress the heading in the report output. Typically variable_name_dep, variable_name_indep, etc. |
replace_heading_for_group |
Replacing heading for group
Occasionally, one needs to replace the heading with another piece of information in the refined chapter_structure. For instance, one may want to organize output by variable_name_indep, but to display the variable_label_indep instead. Use the name for the replacement and the value for the original. |
prefix_heading_for_group , suffix_heading_for_group |
Prefix and suffix headings
Names are heading_groups, values are the prefixes and suffixes. Note
that prefixes should end with a |
require_common_categories |
Check common categories
Whether to check if all items share common categories. |
combined_report |
Create a combined report?
Whether to create a qmd file that merges all chapters into a combined report. |
write_qmd |
Toggle whether to make qmd-files
Sometimes it is useful to only create chapter_dataset files if these have been updated, without having to overwrite the qmd files. |
attach_chapter_dataset |
Toggle inclusion of chapter-specific datasets in qmd-files
Whether to save in each chapter folder an 'Rds'-file with the chapter-specific dataset, and load it at the top of each QMD-file. |
auxiliary_variables |
Auxiliary variables to be included in datasets
Column names in |
serialized_format |
Serialized format
Format for serialized data when storing chapter dataset.
One of |
max_path_warning_threshold |
Maximum number of characters in paths warning
Microsoft has set an absolute limit of 260 characters for its Sharepoint/OneDrive file paths. This will mean that files with cache (hash suffixes are added) will quickly breach this limit. When set, a warning will be returned if files are found to be longer than this threshold. Also note that spaces count as three characters due to its URL-conversion: %20. To avoid test, set to Inf |
filename_prefix |
Prefix string for all qmd filenames
For mesos setup it might be useful to set these files (and related sub-folders) with an underscore
( |
data_filename_prefix |
String attached to beginning of data-file and data-object
|
report_includes_prefix , report_includes_suffix |
Strings around files in report.qmd
The prefix and suffix for each of the chapters being included in the report.qmd file if |
log_file |
Path to log file
Path to log file. Set to NULL to disable logging. |
Details
Note that saros treats data as they are stored: numeric, integer, factor, ordinal, character, and datetime. Currently, only factor/ordinal and character are implemented.
Value
The path
-argument.
Examples
ex_survey_ch_structure <-
refine_chapter_overview(
chapter_overview = ex_survey_ch_overview,
data = ex_survey
)
index_filepath <-
draft_report(
chapter_structure = ex_survey_ch_structure,
data = ex_survey,
path = tempdir()
)
ex_survey: Mockup dataset of a survey.
Description
A dataset containing fake respondents' answers to survey questions. The first two, x_sex and x_human, are intended to be independent variables, whereas the remaining are dependent. The underscore _ in variable names separates item groups (prefix) from items (suffix) (i.e. a_1-a_9 => a + 1-9), whereas ' - ' separates the same for labels. The latter corresponds with the default in SurveyXact.
Usage
ex_survey
Format
A data frame with 100 rows and 29 variables:
- x1_sex
Gender
- x2_human
Is respondent human?
- x3_nationality
Where is the respondent born?
- a_1
Do you consent to the following? - Agreement #1
- a_2
Do you consent to the following? - Agreement #2
- a_3
Do you consent to the following? - Agreement #3
- a_4
Do you consent to the following? - Agreement #4
- a_5
Do you consent to the following? - Agreement #5
- a_6
Do you consent to the following? - Agreement #6
- a_7
Do you consent to the following? - Agreement #7
- a_8
Do you consent to the following? - Agreement #8
- a_9
Do you consent to the following? - Agreement #9
- b_1
How much do you like living in - Beijing
- b_2
How much do you like living in - Brussels
- b_3
How much do you like living in - Budapest
- c_1
How many years of experience do you have in - Company A
- c_2
How many years of experience do you have in - Company B
- d_1
Rate your degree of confidence doing the following - Driving
- d_2
Rate your degree of confidence doing the following - Drinking
- d_3
Rate your degree of confidence doing the following - Driving
- d_4
Rate your degree of confidence doing the following - Dancing
- e_1
How often do you do the following? - Eat
- e_2
How often do you do the following? - Eavesdrop
- e_3
How often do you do the following? - Exercise
- e_4
How often do you do the following? - Encourage someone whom you have only recently met and who struggles with simple tasks that they cannot achieve by themselves
- p_1
To what extent do you agree or disagree to the following policies - Red Party
- p_2
To what extent do you agree or disagree to the following policies - Green Party
- p_3
To what extent do you agree or disagree to the following policies - Yellow Party
- p_4
To what extent do you agree or disagree to the following policies - Blue Party
- f_uni
Which of the following universities would you prefer to study at?
- open_comments
Do you have any comments to the survey?
- resp_status
Response status
ex_survey_ch_overview: Mock overview of chapter structure
Description
Note that only chapter and dep are compulsory.
Usage
ex_survey_ch_overview
Format
A data frame with 5 rows (chapters) and 5 variables:
- chapter
Manual entry chapter title
- author
Single, or multiple authors separated by semicolon
- dep
Columns in ex_survey having the role of dependent variable
- indep
Columns in ex_survey having the role of independent variable
- irrelevant_col
Just a column about something else to verify that the system works also with superfluous information.
File/folder name sanitizer replacing space and punctuation with underscore
Description
File/folder name sanitizer replacing space and punctuation with underscore
Usage
filename_sanitizer(
x,
max_chars = NA_integer_,
accept_hyphen = FALSE,
sep = "_",
valid_obj = FALSE,
to_lower = FALSE,
make_unique = TRUE
)
Arguments
x |
Character vector of file/folder names |
max_chars |
Maximum character length |
accept_hyphen |
Flag, whether a hyphen - is acceptable. |
sep |
String, replacement for illegal characters and spaces. |
valid_obj |
Flag, whether output should be valid as R object name. |
to_lower |
Flag, whether to force all characters to lower. |
make_unique |
Flag, whether all should be unique. |
Value
Character vector of same length as x
Examples
filename_sanitizer(c("Too long a name", "with invalid *^/&#"))
Generate A Quarto Survey Report
Description
This function generates a set of saros chapters, collectively called a report.
Usage
gen_qmd_chapters(
chapter_structure,
data,
authors_col = "author",
path = NULL,
ignore_heading_for_group = NULL,
replace_heading_for_group = NULL,
prefix_heading_for_group = NULL,
suffix_heading_for_group = NULL,
chapter_yaml_file = NULL,
chapter_qmd_start_section_filepath = NULL,
chapter_qmd_end_section_filepath = NULL,
write_qmd = TRUE,
attach_chapter_dataset = TRUE,
auxiliary_variables = NULL,
serialized_format = "rds",
filename_prefix = "",
data_filename_prefix = "data_"
)
Arguments
chapter_structure |
What goes into each chapter and sub-chapter
Data frame (or tibble, possibly grouped). One row per chapter. Should contain the columns 'chapter' and 'dep', Optionally 'indep' (independent variables) and other informative columns as needed. |
data |
Survey data
A data frame (or a srvyr-object) with the columns specified in the chapter_structure 'dep', etc columns. |
authors_col |
Column name for author
Only used if it exists. Multiple authors are separated by semicolon (and optionally with a subsequent space). |
path |
Output path
Path to save all output. Defaults to a temporary directory. |
ignore_heading_for_group |
Ignore heading for group
Type of refined chapter_structure data for which to suppress the heading in the report output. Typically variable_name_dep, variable_name_indep, etc. |
replace_heading_for_group |
Replacing heading for group
Occasionally, one needs to replace the heading with another piece of information in the refined chapter_structure. For instance, one may want to organize output by variable_name_indep, but to display the variable_label_indep instead. Use the name for the replacement and the value for the original. |
prefix_heading_for_group , suffix_heading_for_group |
Prefix and suffix headings
Names are heading_groups, values are the prefixes and suffixes. Note
that prefixes should end with a |
chapter_yaml_file |
Path to YAML-file to insert into each chapter qmd-file
Path to file used to insert header YAML, in each chapter. |
write_qmd |
Toggle whether to make qmd-files
Sometimes it is useful to only create chapter_dataset files if these have been updated, without having to overwrite the qmd files. |
attach_chapter_dataset |
Toggle inclusion of chapter-specific datasets in qmd-files
Whether to save in each chapter folder an 'Rds'-file with the chapter-specific dataset, and load it at the top of each QMD-file. |
auxiliary_variables |
Auxiliary variables to be included in datasets
Column names in |
serialized_format |
Serialized format
Format for serialized data when storing chapter dataset.
One of |
filename_prefix |
Prefix string for all qmd filenames
For mesos setup it might be useful to set these files (and related sub-folders) with an underscore
( |
data_filename_prefix |
String attached to beginning of data-file and data-object
|
Details
A report consists of multiple chapters, an index file, and optionally a combined report file that merges them together. A chapter can contain any user-defined set of dependent, independent or bivariate variable sets. A chapter consists of multiple sections. A section is defined as a group in the chapter_structure (ignoring the chapter grouping level) containing variables of the same type, meaning at a minimum that the variables in the section sharing the same response options, the same main question, and being of the same data type.
Value
Side-effects: qmd-files generated in the specified working directory.
Generate Quarto Index File That Merges All Chapters
Description
This function creates an index Quarto file (QMD) that merges all chapters in the specified order. It can also include optional title and author(s) information.
Usage
gen_qmd_file(
path = NULL,
filename = "report",
yaml_file = NULL,
qmd_start_section_filepath = NULL,
qmd_end_section_filepath = NULL,
chapter_structure = NULL,
include_files = NULL,
title = NULL,
authors = NULL,
output_formats = NULL,
output_filename = NULL,
includes_prefix = "{{< include \"",
includes_suffix = "\" >}}",
call = rlang::caller_env()
)
Arguments
path |
String, where to write qmd-file. |
filename |
String, bare name of qmd-file. Default: "report". If NULL, generates a sanitized version of the title. If both filename and title are NULL, errors. |
yaml_file |
A string containing the filepath to a yaml-file to be inserted at top of qmd-file. |
qmd_start_section_filepath , qmd_end_section_filepath |
String, filepath to a qmd-file inserted at start and end of file. |
chapter_structure |
What goes into each chapter and sub-chapter
Data frame (or tibble, possibly grouped). One row per chapter. Should contain the columns 'chapter' and 'dep', Optionally 'indep' (independent variables) and other informative columns as needed. |
title |
Title of report
Added automatically to YAML-header of index.qmd and report.qmd-files. |
authors |
Authors of entire report
If NULL, infers from |
output_filename , output_formats |
Character. If applied, will construct
list of links to files with said |
call |
Internal call argument. Not to be fiddled with by the user. |
Value
A string containing the filepath to the generated Quarto report file.
Generate YAML File from Directory Structure
Description
Generate YAML File from Directory Structure
Usage
generate_yaml_from_directory(
input_path = tempdir(),
output_yaml_path = "_project_structure_en.yaml",
remove_prefix_numbers = FALSE
)
Arguments
input_path |
String. The path to the directory whose structure needs to be captured. |
output_yaml_path |
String. The path where the YAML file will be saved. |
remove_prefix_numbers |
Boolean. Whether to remove numeric prefixes and any resulting leading non-alphanumeric characters from folder names. Defaults to FALSE. |
Value
No return value, called for side effects
Examples
generate_yaml_from_directory(
output_yaml_path =
tempfile("_project_structure_en", fileext = ".yaml")
)
Get Global Options for Chunk Templates
Description
Get Global Options for Chunk Templates
Usage
get_chunk_template_defaults(variant = 1)
Arguments
variant |
Positive integer. |
Value
List with options in R
Examples
get_chunk_template_defaults()
Get Core Chapter Structure Column Names
Description
Returns the vector of core column names available as organize_by options.
Usage
get_organize_by_opts()
Value
A character vector.
Examples
get_organize_by_opts()
Helper function to extract raw variable labels from the data
Description
Helper function to extract raw variable labels from the data
Usage
get_raw_labels(data, col_pos = NULL, return_as_list = FALSE)
Arguments
data |
Dataset |
col_pos |
Optional, character vector of column names or integer vector of positions |
return_as_list |
Flag, whether to return as list or character vector |
Value
List or character vector
Handle Maximum Observed Numbering
Description
Handle Maximum Observed Numbering
Usage
handle_max_observed(parent_path, count_existing_folders = FALSE)
Arguments
parent_path |
String. The path to the parent directory. |
count_existing_folders |
Boolean. Whether to count existing folders for numbering. |
Value
String. Appropriate numbering based on the maximum observed value.
Handle Naming Conventions
Description
Handle Naming Conventions
Usage
handle_naming_conventions(
name = "Journal manuscripts",
case = "asis",
word_separator = NULL,
replacement_list = NULL
)
Arguments
name |
String. Original folder name. |
case |
String. One of c("asis", "sentence", "lower", "upper", "title", "snake"). |
word_separator |
String. |
replacement_list |
Character vector, named. |
Value
String. Modified folder name.
Handle numbering inheritance
Description
Handle numbering inheritance
Usage
handle_numbering_inheritance(
counter = 1,
numbering_prefix = c("none", "max_global", "max_local"),
max_folder_count_digits = 0,
parent_path = "Journal manuscripts",
parent_numbering = NA,
numbering_parent_child_separator = "_",
count_existing_folders = FALSE
)
Arguments
counter |
digit |
numbering_prefix |
One of "none" (no zero-leading prefix), "max_global" (counts with leading zeroes matching the maximally observed items in any of the subfolders), "max_local" (same as max_global, but only considering the current folder of the item) |
max_folder_count_digits |
Integer. The fixed width of the counting. |
parent_path |
String, path to parent folder. |
parent_numbering |
String, or NA. If not NA, adds the parent_numbering to the left side of the counter. |
numbering_parent_child_separator |
String, separates the parent number from the child number, if parent_numbering is not NA. |
count_existing_folders |
Flag. Whether to consider existing folders when counting. Defaults to FALSE. |
Value
String
Initialize Folder Structure
Description
Can be used programatically from the console, or simply use the New Project Wizard.
Usage
initialize_saros_project(
path,
structure_path = NULL,
numbering_prefix = c("none", "max_local", "max_global"),
numbering_inheritance = TRUE,
word_separator = NULL,
numbering_name_separator = " ",
replacement_list = NULL,
numbering_parent_child_separator = word_separator,
case = c("asis", "sentence", "title", "lower", "upper", "snake"),
count_existing_folders = FALSE,
r_files_out_path = NULL,
r_files_source_path = system.file("templates", "r_files.csv", package = "saros.base"),
r_optionals = TRUE,
r_add_file_scope = TRUE,
r_prefix_file_scope = "### ",
r_add_folder_scope_as_README = FALSE,
create = TRUE
)
Arguments
path |
String, path to where to create the project files |
structure_path |
String. Path to the YAML file that defines the folder structure. Defaults to system.file("templates", "_project_structure_en.yaml"). |
numbering_prefix |
String. One of c("none", "max_local", "max_global"). |
numbering_inheritance |
Flag. Whether to inherit numbering from parent folder. |
word_separator |
String. Replace separators between words in folder names. Defaults to NULL. |
numbering_name_separator |
String. Separator between numbering part and name. |
replacement_list |
named character vector. Each name in this vector will be replaced with its |
numbering_parent_child_separator |
String. Defaults to word_separator. |
case |
String. One of c("asis", "sentence", "lower", "upper", "title", "snake"). |
count_existing_folders |
Boolean. Defaults to FALSE. |
r_files_out_path |
String, path to where to place R placeholder files. If NULL, will not create any. |
r_files_source_path |
String, path to where to find CSV-field containing the columns folder_name, folder_scope, file_name, file_scope. If NULL, defaults to system.file("templates", "r_files.csv")). |
r_optionals |
Flag. Whether to add files marked as 1 (or TRUE) in the optional column. Defaults to TRUE. |
r_add_file_scope |
Flag. Whether to add value from column 'file_scope' to beginning of each file. Default to TRUE. |
r_prefix_file_scope |
String to add before file_scope. Defaults to "### " |
r_add_folder_scope_as_README |
Flag. Whether to create README file in each folder with the folder_scope column cell in r_files_source_path. Defaults to FALSE. |
create |
Boolean. Defaults to TRUE in initialize_saros_project(), FALSE in create_directory_structure(). |
Value
Returns invisibly path
Examples
initialize_saros_project(path = tempdir())
Mass Create Elements of A Certain Type
Description
Mass Create Elements of A Certain Type
Usage
insert_chunk(
chapter_structure_section,
grouping_structure,
template_variable_name = ".template"
)
Arguments
chapter_structure_section |
Overview of chapter section
Data frame (or tibble, possibly grouped). Must contain column 'dep'
with similar items. See |
grouping_structure |
Vector of groups
Internal usage. |
Value
Named list of elements, where each element can UNFINISHED.
Is x A String?
Description
Returns TRUE if object is a character of length 1.
Usage
is_string(x)
Arguments
x |
Object |
Value
Bool
Read Default Arguments for draft_report()
from YAML-file
Description
Read Default Arguments for draft_report()
from YAML-file
Usage
read_default_draft_report_args(path)
Arguments
path |
|
Value
The defaults as a yaml
-object.
Examples
tmpfile <- tempfile(fileext = ".yaml")
write_default_draft_report_args(path = tmpfile)
read_default_draft_report_args(path = tmpfile)
Processes A 'chapter_overview' Data Frame
Description
Processes A 'chapter_overview' Data Frame
Usage
refine_chapter_overview(
chapter_overview = NULL,
data = NULL,
chunk_templates = NULL,
label_separator = " - ",
name_separator = NULL,
single_y_bivariates_if_indep_cats_above = 3,
single_y_bivariates_if_deps_above = 20,
always_show_bi_for_indep = NULL,
hide_bi_entry_if_sig_above = 1,
hide_chunk_if_n_below = 10,
hide_variable_if_all_na = TRUE,
keep_dep_indep_if_no_overlap = FALSE,
organize_by = c("chapter", ".variable_label_prefix_dep", ".variable_name_indep",
".template_name"),
arrange_section_by = c(.chapter_number = FALSE, .variable_name_dep = FALSE,
.variable_name_indep = FALSE, .template_name = FALSE),
na_first_in_section = TRUE,
max_width_obj = 128,
max_width_chunk = 128,
max_width_file = 64,
max_width_folder_name = 12,
sep_obj = "_",
sep_chunk = "-",
sep_file = "-",
filename_prefix = "",
...,
progress = TRUE,
variable_group_dep = ".variable_group_dep",
variable_group_prefix = NULL,
n_range_glue_template_1 = "{n}",
n_range_glue_template_2 = "[{n[1]}-{n[2]}]",
log_file = NULL
)
Arguments
chapter_overview |
What goes into each chapter and sub-chapter
Data frame (or tibble, possibly grouped). One row per chapter. Should contain the columns 'chapter' and 'dep', Optionally 'indep' (independent variables) and other informative columns as needed. |
data |
Survey data
A data frame (or a srvyr-object) with the columns specified in the chapter_structure 'dep', etc columns. |
chunk_templates |
Chunk templates
Must contain columns |
label_separator |
Variable label separator
String to split labels on main question and sub-items. |
name_separator |
Variable name separator
String to split column names in data between main question and sub-items |
single_y_bivariates_if_indep_cats_above |
Single y bivariates if indep-cats above ...
Figures and tables for bivariates can become very long if the independent variable has many categories. This argument specifies the number of indep categories above which only single y bivariates should be shown. |
single_y_bivariates_if_deps_above |
Single y bivariates if dep-vars above ...
Figures and tables for bivariates can become very long if there are many dependent variables in a battery/question matrix. This argument specifies the number of dep variables above which only single y bivariates should be shown. Set to 0 to always show single y bivariates. |
always_show_bi_for_indep |
Always show bivariate for indep-variable
Specific combinations with a by-variable where bivariates should always be shown. |
hide_bi_entry_if_sig_above |
p-value threshold for hiding bivariate entry
Whether to hide bivariate entry if significance is above this value. Defaults to showing all. |
hide_chunk_if_n_below |
Hide result if N below
Whether to hide result if N for a given dataset is below this value. NOTE: Exceptions will be made to chr_table and chr_plot as these are typically exempted in the first place. This might change in the future with a separate argument. |
hide_variable_if_all_na |
Hide variable from outputs if containing all NA
Whether to remove variables if all values are NA. |
keep_dep_indep_if_no_overlap |
Keep dep-indep if no overlap
Whether to keep dep-indep rows if there is no overlap. |
organize_by |
Grouping columns
Column names used for identifying chapters and sections. |
arrange_section_by |
Grouping columns
Column names used for sorting section within each organize_by group. If character vector, will assume all are to be arranged in ascending order. If a named logical vector, FALSE will indicate ascending, TRUE descending. Defaults to sorting in ascending order (alphabetical) for commonly needed variable name/label info, and in descending order for chunk_templates as one typically wants univariates before bivariates. |
na_first_in_section |
Whether to place NAs first when sorting
Default ascending and descending sorting with |
max_width_obj , max_width_chunk , max_width_file |
Maximum object width
Maximum width for names of objects (in R/Python environment),
chunks (#| label: ) and optional files. Note, will always replace variable
labels with variable names, to avoid very long file names.
Note for filenames: Due to OneDrive having a max path of about
400 characters, this can quickly be exceeded with a long path base path,
long file names if using labels as part of structure, and hashing with
Quarto's |
max_width_folder_name |
Maximum clean folder name length
Whereas |
sep_obj , sep_chunk , sep_file |
Separator string
Separator to use between grouping variables. Defaults to underscore for object names and hyphen for chunk labels and file names. |
filename_prefix |
Prefix string for all qmd filenames
For mesos setup it might be useful to set these files (and related sub-folders) with an underscore
( |
... |
Dynamic dots Arguments forwarded to the corresponding functions that create the elements. |
progress |
Whether to display progress message
Mostly useful when hide_bi_entry_if_sig_above < 1 |
variable_group_dep |
Name for the variable_group_dep column
This column is used to group variables that are part of the same bivariate analysis. |
variable_group_prefix |
Set a prefix to more easily find it in your labels
By default, the .variable_group column is just integers. If you wish to use this as part of your object/label/filename numbering scheme, a number by itself will not be very informative. Hence you could set a prefix such as "Group" to distinguish this column from other columns in the chapter_structure. |
n_range_glue_template_1 , n_range_glue_template_2 |
Glue templates for the n_range columns to be created. |
log_file |
Path to log file
Path to log file. Set to NULL to disable logging. |
Value
Grouped tibble.
Examples
ref_df <- refine_chapter_overview(
chapter_overview = ex_survey_ch_overview
)
Removes entries in sidebar if containing a filename regex pattern.
Description
Removes entries in sidebar if containing a filename regex pattern.
Usage
remove_entry_from_sidebar(
path = "_site",
filename_as_regex = c("report\\.pdf", "report\\.docx")
)
Arguments
path |
String, path to where your html-files are located. Defaults to "_site" |
filename_as_regex |
Character vector of regex patterns to search for. Defaults to c("report\.pdf", "report\.docx") |
Value
Invisibly returns files processed
Post-render rendering of complete reports
Description
If one wishes to render complete reports that are linked to in a website, but not listed among the chapters on the sidebar menu, one can make these with filenames starting with underscores (_) which will make them not listed in said menu. However, this will also mean they are not rendered in a Quarto (Website) project. This function, which can be called within a post-script (see example below), will render only these after the ordinary rendering of the project, and copied to the _site folder.
Usage
render_full_reports(
files = NULL,
path,
processable_path = file.path(path, "Reports"),
site_path = file.path(path, "_site"),
resource_paths = file.path(path, c("_extensions", "_images")),
warn_on_file_error = FALSE,
...
)
Arguments
files |
Optional character vector of report files (qmd). Can be obtained within a project by |
path |
If no files are given, a path to the root folder of the local "site". |
processable_path |
Path to where report files can be (recursively) found. |
site_path |
Path to _site |
resource_paths |
Paths to where _extensions and _images folders can be found and copied to wherever needed |
warn_on_file_error |
If TRUE, will collect warnings if a file fails to render or be copied. If FALSE (default), will stop the rendering process. |
... |
Additional arguments passed to |
Value
Returns invisibly a character vector of processed files.
Setup files needed for basic password-based access restriction for website
Description
Create a _headers file for 'Netlify' publishing or a set of .htaccess and .htpasswd files (FTP) placed in the specific subfolders.
Usage
setup_access_restrictions(
remote_basepath = "/home/",
local_basepath,
rel_path_base_to_parent_of_user_restricted_folder = file.path("Reports", "2022",
"Mesos"),
warn = TRUE,
local_main_password_path = ".main_htpasswd_public",
username_folder_matching_df = NULL,
universal_usernames = c("admin"),
log_rounds = 12,
append_users = TRUE,
password_input = "prompt",
type = c("netlify", "apache")
)
Arguments
remote_basepath |
String. Folder where site will be located if using FTP-server. Needed for .htaccess-files. |
local_basepath |
String. Local folder for website, typically "_site". |
rel_path_base_to_parent_of_user_restricted_folder |
String, relative path from basepath to the folder where the restricted folders are located. (E.g. the "mesos"-folder) |
warn |
Flag. Whether to provide warning or error if paths do not exist. |
local_main_password_path |
String. Path to main file containing all usernames and passwords formatted with a colon between username and password. |
username_folder_matching_df |
Data frame. If NULL (default), will use folder names as usernames. Otherwise, a data frame with two columns: "folder" and "username" where "folder" is the name of the folder and "username" is the username for that folder. |
universal_usernames |
Character vector. Usernames in local_main_htpasswd_path which always have access to folder |
log_rounds |
Integer, number of rounds in the bcrypt algorithm. The higher the more time consuming and harder to brute-force. |
append_users |
Boolean, if TRUE (default) will create new users and add them to local_main_password_path. See also password_input. |
password_input |
String, either "prompt" which asks the user for input. Alternatively, a number stored as string for a generated random password of said length: "8", "10", "12", "16" |
type |
Character vector. "netlify" will create _headers file used for Netlify. "apache" will create .htaccess and .htpasswd files used for general FTP-servers. |
Value
String, the path to the newly created _headers-file or .htaccess files.
Simply create qmd-files and yml-files for mesos reports
Description
Simply create qmd-files and yml-files for mesos reports
Usage
setup_mesos(
main_directory = character(),
mesos_var_subfolder = character(),
files_to_process,
mesos_df,
files_taking_title = c("index.qmd", "report.qmd"),
read_syntax_pattern = "qs::qread\\('",
read_syntax_replacement = "qs::qread('../../",
qmd_regex = "\\.qmd",
subtitle_separator = " - ",
prefix = "{{< include \"",
suffix = "\" >}}"
)
Arguments
main_directory |
String, path to where the _metadata.yml, stub QMD-files and their subfolders are created. |
mesos_var_subfolder |
String, optional name of a subfolder of the mesos_var folder in where to place all mesos_group folders. |
files_to_process |
Character vector of files used as templates for the mesos stubs. |
mesos_df |
List of single-column data frames where each variable is a mesos variable, optionally with a variable label indicating its pretty name. The values in each variable are the mesos groups. NA is silently ignored. |
files_taking_title |
Character vector of files for which titles should be set. Optional but recommended. |
read_syntax_pattern , read_syntax_replacement |
Optional strings, any regex pattern to search and replace in the qmd-files. If NULL, will ignore it. |
qmd_regex |
String. Experimental feature for allowing Rmarkdown, not yet tested. |
subtitle_separator |
String or NULL. If a string will add title and subtitle fields to the _metadata.yml-files in the deepest child folders. The title is the mesos_group. The subtitle is a concatenation of the folder name of the main_directory and the mesos_var label. |
prefix , suffix |
String for the include section of the stub qmd files. |
Write Default Arguments for draft_report()
to YAML-file
Description
Write Default Arguments for draft_report()
to YAML-file
Usage
write_default_draft_report_args(
path,
ignore_args = c("data", "...", "dep", "indep", "chapter_structure", "chapter_overview",
"path")
)
Arguments
path |
|
ignore_args |
A character vector of argument (names) not to be written to file. |
Value
The defaults as a yaml
-object.
Examples
write_default_draft_report_args(path = tempfile(fileext = ".yaml"))