| Title: | Survey Instrument Workflows |
| Version: | 0.3.4 |
| Description: | Supports survey research workflows built around a typed instrument object (the sframe). Features include visual instrument design via a browser-based builder or 'Shiny' studio, export to a self-contained static HTML survey, an embeddable 'Shiny' module, SHA-256 integrity-checked serialisation to the '.sframe' format, multi-page survey rendering, branching logic, response quality checking, scale scoring, psychometric diagnostics, analysis-plan execution, model syntax planning, an interactive response dashboard, codebook generation, and reproducible HTML reporting. |
| License: | MIT + file LICENSE |
| URL: | https://mohammedalisharafuddin.github.io/surveyframe/, https://github.com/MohammedAliSharafuddin/surveyframe |
| BugReports: | https://github.com/MohammedAliSharafuddin/surveyframe/issues |
| Encoding: | UTF-8 |
| Language: | en-GB |
| Depends: | R (≥ 4.1.0) |
| Imports: | jsonlite (≥ 1.8.0), rlang (≥ 1.1.0), openssl (≥ 2.1.0) |
| Suggests: | ggplot2 (≥ 3.4.0), googlesheets4 (≥ 1.1.0), shiny (≥ 1.7.0), psych (≥ 2.3.0), MASS, nnet, digest (≥ 0.6.0), lavaan (≥ 0.6-0), testthat (≥ 3.0.0), knitr, rmarkdown, naniar (≥ 1.0.0), pagedown (≥ 0.20) |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| Config/roxygen2/version: | 8.0.0 |
| RoxygenNote: | 8.0.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-07-24 22:04:00 UTC; maxx |
| Author: | Mohammed Ali Sharafuddin
|
| Maintainer: | Mohammed Ali Sharafuddin <mohammedali.page@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-07-24 23:00:02 UTC |
surveyframe: Survey Instrument Workflows for R
Description
surveyframe defines a survey instrument as a first-class R object and supports a complete workflow from questionnaire design through data collection, quality checking, scoring, psychometric diagnostics, and reproducible reporting. The package covers static HTML survey export, an embeddable Shiny survey module, an interactive response dashboard, a role-based analysis planner with pre-declared research questions, common survey statistics, and model syntax planning for EFA, CFA, CB-SEM, and PLS-SEM.
Core workflow
-
Design an instrument with
launch_builder()orsf_instrument()and its component constructors:sf_item(),sf_choices(),sf_scale(),sf_branch(),sf_check(). -
Validate and save with
validate_sframe()andwrite_sframe(). -
Deploy a Shiny survey with
render_survey(). -
Load responses with
read_responses()orread_sheet_responses(). -
Check quality with
quality_report(). -
Score and analyse with
score_scales(),descriptives_report(),missing_data_report(),reliability_report(),item_report(),efa_report(),cfa_syntax(), andrun_analysis_plan(). -
Report with
codebook_report(),render_report(), andrender_results().
The instrument object
Every function in the package operates on an sframe object. The object
is the single source of truth for item definitions, scale structure,
reverse-coding keys, branching rules, check specifications, analysis plans,
and optional model specifications.
File format
Instruments are stored as UTF-8 JSON files with the .sframe extension.
Each file includes a SHA-256 integrity hash for reproducibility auditing.
Author(s)
Maintainer: Mohammed Ali Sharafuddin mohammedali.page@gmail.com (ORCID)
Authors:
Mohammed Ali Sharafuddin mohammedali.page@gmail.com (ORCID)
See Also
Useful links:
Report bugs at https://github.com/MohammedAliSharafuddin/surveyframe/issues
Add a model specification to an instrument
Description
Add a model specification to an instrument
Usage
add_model(instrument, model, validate = TRUE, replace = TRUE)
Arguments
instrument |
An |
model |
An |
validate |
Logical. Whether to validate the model against the instrument before adding it. |
replace |
Logical. Whether to replace an existing model with the same
ID. Defaults to |
Value
The updated sframe object.
Assumption-check report
Description
Performs common assumption checks for survey analyses using base R where possible: Shapiro-Wilk tests, skewness/kurtosis screening, Levene and Brown-Forsythe tests, regression residual checks, VIF, Cook's distance, expected-count checks, and sparse-cell warnings.
Usage
assumption_report(
data,
variables = NULL,
group = NULL,
outcome = NULL,
predictors = NULL,
table_vars = NULL
)
Arguments
data |
A data.frame. |
variables |
Numeric variables for normality screening. |
group |
Optional grouping variable for Levene/Brown-Forsythe tests. |
outcome |
Optional regression outcome. |
predictors |
Optional regression predictors. |
table_vars |
Optional two categorical variables for expected-count checks. |
Value
An object of class sframe_assumption_report.
Percentile bootstrap confidence interval for a statistic
Description
Resamples x with replacement R times, applies FUN to each resample,
and returns the percentile interval of the resampled statistics together
with the observed value.
Usage
bootstrap_ci(x, FUN = stats::median, R = 2000, conf.level = 0.95, seed = NULL)
Arguments
x |
A numeric vector. |
FUN |
A function of one vector returning a single number. Defaults
to |
R |
Integer. Number of bootstrap resamples. Defaults to 2000. |
conf.level |
Confidence level. Defaults to 0.95. |
seed |
Integer or NULL. When supplied, sets the random seed so the interval is reproducible. |
Value
A named numeric vector: estimate, lower, upper. The bounds
are NA when x has fewer than 3 finite values.
See Also
cohens_d_ci(), cramers_v_ci(), eta_sq_ci()
Examples
bootstrap_ci(mtcars$mpg, seed = 42)
bootstrap_ci(mtcars$mpg, FUN = mean, conf.level = 0.90, seed = 42)
Generate lavaan CFA syntax
Description
Generate lavaan CFA syntax
Usage
cfa_lavaan_syntax(
instrument = NULL,
model = NULL,
scales = NULL,
ordered = FALSE,
std_lv = TRUE,
residual_covariances = NULL,
latent_covariances = TRUE
)
Arguments
instrument |
Optional |
model |
Optional |
scales |
Optional scale IDs when deriving a model from an instrument. |
ordered |
Logical. Whether to add an ordered-item note. |
std_lv |
Logical. Whether to add a |
residual_covariances |
Optional list of |
latent_covariances |
Logical. Whether to include model-level latent
covariances supplied in |
Value
A lavaan syntax string.
Generate lavaan CFA syntax from an instrument object
Description
Produces a character string of lavaan model syntax derived from the
scale structure in the instrument. The syntax can be passed directly to
lavaan::cfa(). Reverse-coded items are noted in a comment but are not
transformed in the syntax; recoding should be applied to the data before
fitting the model.
Usage
cfa_syntax(instrument, scales = NULL, std_lv = TRUE)
Arguments
instrument |
An |
scales |
Character vector or NULL. A subset of scale IDs to include. When NULL, all scales are included. |
std_lv |
Logical. Whether to include the |
Value
A character string of lavaan CFA model syntax.
See Also
efa_report(), reliability_report()
Examples
cs <- sf_choices("ag5", 1:5,
c("Strongly disagree", "Disagree", "Neutral",
"Agree", "Strongly agree"))
i1 <- sf_item("sat_1", "Item 1", type = "likert",
choice_set = "ag5", scale_id = "sat")
i2 <- sf_item("sat_2", "Item 2", type = "likert",
choice_set = "ag5", scale_id = "sat")
i3 <- sf_item("sat_3", "Item 3 (reverse)", type = "likert",
choice_set = "ag5", scale_id = "sat", reverse = TRUE)
scale <- sf_scale("sat", "Satisfaction",
items = c("sat_1", "sat_2", "sat_3"))
instr <- sf_instrument("Demo Survey", components = list(cs, i1, i2, i3, scale))
syntax <- cfa_syntax(instr)
cat(syntax)
## Not run:
# lavaan is not installed by default; install it before fitting.
demo <- sframe_demo_data()
scored <- score_scales(demo$responses, demo$instrument)
fit <- lavaan::cfa(syntax, data = scored, std.lv = TRUE)
summary(fit, fit.measures = TRUE)
## End(Not run)
Generate a survey codebook from an instrument object
Description
Produces a structured codebook listing all items, their types, choice sets, scale membership, and reverse-coding status. The codebook can be rendered as HTML or Markdown.
Usage
codebook_report(instrument, format = c("html", "md"))
Arguments
instrument |
An |
format |
Character. Output format. Either |
Value
An object of class sframe_codebook, a list with elements
instrument_meta, items_table, choices_table, and scales_table.
Call print() to display a compact summary or use render_report() to
include the codebook in a full report.
See Also
Examples
cs <- sf_choices("ag5", 1:5,
c("Strongly disagree", "Disagree", "Neutral",
"Agree", "Strongly agree"))
i1 <- sf_item("sat_1", "Item 1", type = "likert",
choice_set = "ag5", scale_id = "sat")
i2 <- sf_item("sat_2", "Item 2", type = "likert",
choice_set = "ag5", scale_id = "sat")
scale <- sf_scale("sat", "Satisfaction", items = c("sat_1", "sat_2"))
instr <- sf_instrument("Demo Survey", components = list(cs, i1, i2, scale))
cb <- codebook_report(instr)
print(cb)
nrow(cb$items_table)
nrow(cb$scales_table)
Bootstrap confidence interval for Cohen's d
Description
Percentile bootstrap for the standardised mean difference between two independent groups. Each resample draws within each group, preserving the group sizes.
Usage
cohens_d_ci(x, y, R = 2000, conf.level = 0.95, seed = NULL)
Arguments
x, y |
Numeric vectors, one per group. |
R |
Integer. Number of bootstrap resamples. Defaults to 2000. |
conf.level |
Confidence level. Defaults to 0.95. |
seed |
Integer or NULL. When supplied, sets the random seed. |
Value
A named numeric vector: estimate, lower, upper. The bounds
are NA when either group has fewer than 3 finite values.
See Also
Examples
cohens_d_ci(mtcars$mpg[mtcars$am == 1], mtcars$mpg[mtcars$am == 0],
seed = 42)
Bootstrap confidence interval for Cramer's V
Description
Percentile bootstrap for the association strength in a contingency table. The table is expanded back to individual observations, which are resampled jointly. For a 2 by 2 table the statistic equals phi.
Usage
cramers_v_ci(tab, R = 2000, conf.level = 0.95, seed = NULL)
Arguments
tab |
A contingency table (from |
R |
Integer. Number of bootstrap resamples. Defaults to 2000. |
conf.level |
Confidence level. Defaults to 0.95. |
seed |
Integer or NULL. When supplied, sets the random seed. |
Value
A named numeric vector: estimate, lower, upper. The bounds
are NA when the table holds fewer than 3 observations.
See Also
Examples
cramers_v_ci(table(mtcars$am, mtcars$cyl), seed = 42)
Descriptive statistics report
Description
Computes survey descriptives for numeric, Likert, and scale-score columns, including missingness, mean, standard deviation, median, IQR, range, skewness, kurtosis, standard error, and confidence intervals.
Usage
descriptives_report(
data,
variables = NULL,
split_by = NULL,
conf_level = 0.95,
weights = NULL
)
Arguments
data |
A data.frame of responses. |
variables |
Character vector of variables. When |
split_by |
Optional grouping variable. |
conf_level |
Confidence level for the mean interval. |
weights |
Optional case-weight column. |
Value
An object of class sframe_descriptives_report.
Prepare a survey instrument for exploratory factor analysis
Description
Reports KMO sampling adequacy, Bartlett's test of sphericity, and a
parallel analysis scree plot to inform factor number selection. The
suggested number of factors from parallel analysis is returned in
$suggested_nfactors. The report
prepares the researcher to estimate an EFA solution with a separate package
such as psych or lavaan.
Usage
efa_report(
data,
instrument,
scales = NULL,
nfactors = NULL,
rotation = "oblimin"
)
Arguments
data |
A |
instrument |
An |
scales |
Character vector or NULL. Scale IDs whose items to include. When NULL, all scale items are pooled. |
nfactors |
Integer or NULL. Suggested number of factors to highlight on the scree plot. When NULL, the parallel analysis recommendation is used. |
rotation |
Character. The rotation method to display in the diagnostic
notes. Does not affect the diagnostics themselves. Defaults to
|
Value
An object of class sframe_efa_report with elements kmo,
bartlett, parallel, and suggested_nfactors.
See Also
reliability_report(), cfa_syntax()
Examples
if (requireNamespace("psych", quietly = TRUE)) {
demo <- sframe_demo_data()
er <- efa_report(demo$responses, demo$instrument)
print(er)
}
Estimate an exploratory factor solution
Description
Runs psych::fa() on selected item columns and returns loadings,
communalities, uniqueness, variance summaries, and simple item retention
flags. The psych package is optional and is only required when this
function is called.
Usage
efa_solution(
data,
instrument,
items = NULL,
scales = NULL,
nfactors = 1L,
extraction = c("minres", "pa", "ml"),
rotation = c("oblimin", "promax", "varimax"),
min_loading = 0.3,
cross_loading = 0.3
)
Arguments
data |
A data.frame of responses. |
instrument |
An |
items |
Character vector of item IDs. When |
scales |
Optional scale IDs used to select item columns. |
nfactors |
Number of factors. |
extraction |
Extraction method passed to |
rotation |
Rotation method passed to |
min_loading |
Minimum salient loading. |
cross_loading |
Maximum secondary loading before a warning is raised. |
Value
An object of class sframe_efa_solution. Alongside the psych
objects it carries three tidy data frames ready for plotting and
reporting: loadings_long (item_id, factor, loading),
communalities_table (item_id, communality, uniqueness), and
variance_table (factor, ss_loadings, proportion_var,
cumulative_var).
Generate EFA planning syntax
Description
Generate EFA planning syntax
Usage
efa_syntax(
items,
nfactors = 1L,
extraction = c("minres", "pa", "ml"),
rotation = c("oblimin", "promax", "varimax"),
data_name = "data"
)
Arguments
items |
Character vector of item IDs. |
nfactors |
Number of factors. |
extraction |
Extraction method. |
rotation |
Rotation method. |
data_name |
Name of the data object in generated R code. |
Value
A character string with R syntax.
Bootstrap confidence interval for eta squared
Description
Percentile bootstrap for the proportion of variance in outcome
explained by group, resampling observations jointly so the group
structure travels with each resample.
Usage
eta_sq_ci(outcome, group, R = 2000, conf.level = 0.95, seed = NULL)
Arguments
outcome |
A numeric vector. |
group |
A grouping vector of the same length. |
R |
Integer. Number of bootstrap resamples. Defaults to 2000. |
conf.level |
Confidence level. Defaults to 0.95. |
seed |
Integer or NULL. When supplied, sets the random seed. |
Value
A named numeric vector: estimate, lower, upper. The bounds
are NA with fewer than 3 complete observations or fewer than 2 groups.
See Also
Examples
eta_sq_ci(mtcars$mpg, mtcars$cyl, seed = 42)
Export a survey instrument to Google Sheets collection format
Description
Generates a Google Apps Script file that, when run in a Google Sheet,
creates a response collection endpoint for a survey instrument. The builder
can store the deployed Apps Script URL in survey metadata, and the same
sheet can be read back with read_sheet_responses().
Usage
export_google_sheet(instrument, sheet_url, output_dir = ".")
Arguments
instrument |
An |
sheet_url |
Character. The URL of an existing Google Sheet. The sheet
must be shared so that anyone with the link can edit, or use service
account credentials via |
output_dir |
Character. Directory to write the Apps Script file. Defaults to the current working directory. |
Value
The path to the generated .gs Apps Script file, invisibly.
See Also
read_sheet_responses(), read_responses(), write_sframe()
Examples
instr <- read_sframe(
system.file("extdata", "tourism_services_demo.sframe",
package = "surveyframe")
)
script <- export_google_sheet(
instr,
sheet_url = "https://docs.google.com/spreadsheets/d/demo",
output_dir = tempdir()
)
file.exists(script)
Export a self-contained static HTML survey
Description
Generates a single HTML file that presents the survey instrument in a browser without requiring a Shiny server or any internet connection. All thirteen item types, branching logic, required-field validation, and multi-page navigation are handled entirely in client-side JavaScript.
Usage
export_static_survey(
instrument,
output_path = NULL,
open = interactive(),
endpoint_url = NULL,
overwrite = FALSE
)
Arguments
instrument |
An |
output_path |
Character. File path for the output HTML. When |
open |
Logical. If |
endpoint_url |
Character or NULL. A URL to which responses are POSTed as JSON on submission. When NULL, CSV download is the only collection mechanism. |
overwrite |
Logical. Whether to overwrite an existing file at
|
Details
When output_path is NULL, the file is written to tempdir(). Supply
an explicit output_path for any production export that should be kept.
When a respondent clicks the submit button, the browser downloads a
one-row CSV file named <survey_title>_response_<id>.csv. If
endpoint_url is supplied, the same payload is also sent as a JSON
POST request to that URL (for example a Google Apps Script web app or a
serverless function). The two mechanisms are independent: the download
happens regardless, so responses are never lost if the POST fails.
The exported file works offline. It can be hosted on GitHub Pages, Netlify, any static file server, or e-mailed as an attachment for opening directly from disk.
Value
The output path, invisibly.
See Also
launch_studio(), launch_builder(), render_survey()
Examples
cs <- sf_choices("ag5", 1:5,
c("Strongly disagree", "Disagree", "Neutral",
"Agree", "Strongly agree"))
i1 <- sf_item("sat_1", "Overall I am satisfied with the service.",
type = "likert", choice_set = "ag5", required = TRUE)
i2 <- sf_item("comments", "Any additional comments?", type = "textarea")
instr <- sf_instrument("Customer Satisfaction Survey",
components = list(cs, i1, i2))
# Write to a temp file without opening the browser
out <- export_static_survey(instr,
output_path = file.path(tempdir(), "sat.html"),
open = FALSE)
file.exists(out)
# Write to a temp file and open in the default browser
export_static_survey(instr,
output_path = file.path(tempdir(), "sat_browser.html"),
overwrite = TRUE)
# Write with a Google Apps Script endpoint for server-side collection
export_static_survey(
instr,
output_path = file.path(tempdir(), "sat_endpoint.html"),
endpoint_url = "https://script.google.com/macros/s/XXXXX/exec",
open = FALSE,
overwrite = TRUE
)
Format an sf_branch object as a string
Description
Format an sf_branch object as a string
Usage
## S3 method for class 'sf_branch'
format(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
A single character string.
Format an sf_check object as a string
Description
Format an sf_check object as a string
Usage
## S3 method for class 'sf_check'
format(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
A single character string.
Format an sf_choices object as a string
Description
Format an sf_choices object as a string
Usage
## S3 method for class 'sf_choices'
format(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
A single character string.
Format an sf_item object as a string
Description
Format an sf_item object as a string
Usage
## S3 method for class 'sf_item'
format(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
A single character string.
Format an sf_model object as a string
Description
Format an sf_model object as a string
Usage
## S3 method for class 'sf_model'
format(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
A single character string.
Format an sf_scale object as a string
Description
Format an sf_scale object as a string
Usage
## S3 method for class 'sf_scale'
format(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
A single character string.
Format an sframe instrument object as a string
Description
Format an sframe instrument object as a string
Usage
## S3 method for class 'sframe'
format(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
A single character string.
Generate item-level diagnostics
Description
Produces item-total correlations, floor and ceiling effect proportions, and item means and standard deviations for each item within each scale.
Usage
item_report(data, instrument, scales = NULL)
Arguments
data |
A |
instrument |
An |
scales |
Character vector or NULL. A subset of scale IDs to analyse. When NULL (default), all scales are included. |
Value
An object of class sframe_item_report, a list with one data.frame
per scale.
See Also
reliability_report(), sf_scale()
Examples
demo <- sframe_demo_data()
ir <- item_report(demo$responses, demo$instrument)
print(ir)
Launch the surveyframe visual survey builder
Description
Opens the SurveyBuilder, a self-contained HTML application for visual survey
design. The builder runs client-side without an R session or Shiny server.
Save instruments as .sframe files from the browser and load them into R
with read_sframe().
Usage
launch_builder(open = TRUE)
Arguments
open |
Logical. When |
Details
The builder includes a three-mode interface.
- Build
An item editor with a persistent inspector panel, drag-to-reorder, undo/redo, and autosave to browser localStorage.
- Preview
A full live render of the survey showing welcome, body, and thank-you pages.
- Analyse
A role-based analysis planner with method-specific options, planned outputs, reporting references, and decision rules.
The builder includes a pure-JavaScript SHA-256 fallback for browsers or
security policies where crypto.subtle is unavailable on file://
origins. Saved .sframe files can be loaded and validated with
read_sframe().
Value
The path to the bundled builder HTML file, invisibly.
See Also
launch_studio(), read_sframe(), run_analysis_plan()
Examples
# Retrieve the builder path for inspection without opening the browser
path <- launch_builder(open = FALSE)
file.exists(path)
Launch SurveyBuilder with the bundled input-types demo preloaded
Description
Opens a temporary copy of the SurveyBuilder with the bundled input-types instrument already injected into the JavaScript state. The demo questions, scales, and analysis plan are visible immediately — no manual file-load step is required.
Usage
launch_builder_demo(open = TRUE)
Arguments
open |
Logical. When |
Value
Invisibly returns a list with builder_path, demo_file, and
responses_path.
Launch the interactive response dashboard
Description
Opens a Shiny dashboard to explore collected response data alongside the
instrument definition. Use this interface after response collection for
analysis and quality control. Use launch_builder() to design new
questionnaires. The dashboard includes five panels:
Usage
launch_dashboard(
instrument = NULL,
responses = NULL,
port = NULL,
host = "127.0.0.1",
launch.browser = interactive()
)
Arguments
instrument |
An |
responses |
A |
port |
Integer or NULL. TCP port for the Shiny server. When NULL, Shiny selects an available port automatically. |
host |
Character. Host address passed to |
launch.browser |
Logical. Whether to open the dashboard in the
default browser automatically. Defaults to |
Details
- Overview
Response count, date range, and instrument metadata.
- Items
Per-item frequency bar charts, histograms, and tabulated frequency counts for choice-type questions.
- Scales
Scale score distributions with mean overlay, and a summary table of scale definitions.
- Quality
Attention check pass rates for each check defined in the instrument.
- Raw data
Scrollable response table with a CSV download button.
The dashboard is read-only and takes its data from R. It has no upload
screen, so pass instrument and responses directly. To open and upload
data interactively, use launch_studio(), which includes this same
dashboard as its Dashboard tab. For a quick look at bundled demo data, use
launch_dashboard_demo().
Value
Called for its side effect. Returns nothing.
See Also
run_analysis_plan(), quality_report(), score_scales()
Examples
## Not run:
# For the bundled demo, use launch_dashboard_demo().
# To upload data interactively, use launch_studio().
# Open the dashboard with your own instrument and responses
instr <- read_sframe(
system.file("extdata", "tourism_services_demo.sframe",
package = "surveyframe")
)
responses <- read_responses(
system.file("extdata", "tourism_services_responses.csv",
package = "surveyframe"),
instr,
respondent_id = "respondent_id",
submitted_at = "submitted_at",
meta_cols = "started_at"
)
launch_dashboard(instr, responses)
## End(Not run)
Launch the response dashboard with the bundled input-types demo
Description
Opens the dashboard with the bundled input-types questionnaire and 120 simulated responses already loaded. The browser is opened automatically by default.
Usage
launch_dashboard_demo(port = NULL, host = "127.0.0.1", launch.browser = TRUE)
Arguments
port |
TCP port for the Shiny server. |
host |
Host address for the Shiny server. |
launch.browser |
Whether to open the browser automatically. Defaults
to |
Value
Called for its side effect.
Launch the SurveyStudio interface
Description
Opens the SurveyStudio Shiny application, a visual interface for the complete surveyframe workflow. The studio includes screens to build a survey draft, open an existing instrument, preview the survey, upload responses, review data quality, inspect reliability, plan analyses, and export outputs.
Usage
launch_studio(
instrument = NULL,
responses = NULL,
respondent_id = NULL,
submitted_at = NULL,
meta_cols = NULL,
strict = TRUE,
screen = c("auto", "build", "preview", "data", "quality", "analysis", "dashboard"),
port = NULL,
host = "127.0.0.1",
launch.browser = interactive()
)
Arguments
instrument |
An |
responses |
A data.frame, tibble, CSV file path, or NULL. |
respondent_id |
Character or NULL. Response ID column when |
submitted_at |
Character or NULL. Submission time column when
|
meta_cols |
Character vector or NULL. Metadata columns when |
strict |
Logical. Passed to |
screen |
Initial studio screen. One of |
port |
TCP port for the Shiny server. |
host |
Host address passed to |
launch.browser |
Whether to open the browser automatically. |
Value
Called for its side effect.
See Also
launch_builder(), launch_dashboard(), read_sframe(),
read_responses()
Examples
## Not run:
launch_studio()
demo <- sframe_demo_data()
launch_studio(instrument = demo$instrument, launch.browser = FALSE)
launch_studio(
instrument = demo$instrument,
responses = demo$responses,
respondent_id = "respondent_id",
submitted_at = "submitted_at"
)
## End(Not run)
Launch SurveyStudio with the bundled input-types demo
Description
Opens SurveyStudio with the bundled input-types questionnaire and simulated response data already loaded. The browser is opened automatically by default.
Usage
launch_studio_demo(
screen = "preview",
port = NULL,
host = "127.0.0.1",
launch.browser = TRUE
)
Arguments
screen |
Initial studio screen. Defaults to |
port |
TCP port for the Shiny server. |
host |
Host address for the Shiny server. |
launch.browser |
Whether to open the browser automatically. Defaults
to |
Value
Called for its side effect.
Missing-data report
Description
Reports item-wise missingness, respondent-wise missingness, missing-data patterns, listwise and pairwise deletion counts, and scale scoring missing rules. No imputation is performed.
Usage
missing_data_report(data, instrument = NULL, variables = NULL)
Arguments
data |
A data.frame of responses. |
instrument |
Optional |
variables |
Optional response columns. Defaults to instrument item IDs when an instrument is supplied, otherwise all columns. |
Value
An object of class sframe_missing_data_report.
Serialise a model specification to JSON
Description
Serialise a model specification to JSON
Usage
model_json(model, pretty = TRUE)
Arguments
model |
An |
pretty |
Logical. Whether to pretty-print the JSON. |
Value
A JSON string.
Create a model reporting template
Description
Create a model reporting template
Usage
model_report_template(model, include_json = TRUE)
Arguments
model |
An |
include_json |
Logical. Whether to include the JSON schema block. |
Value
A character string.
Flag univariate and multivariate outliers
Description
Uses transparent screening rules for numeric survey response variables. The report supports data review before modelling, not automatic deletion.
Usage
outlier_report(
data,
variables = NULL,
method = c("zscore", "iqr", "mahalanobis"),
z_cut = 3,
iqr_multiplier = 1.5,
p_cut = 0.975
)
Arguments
data |
A data.frame. |
variables |
Character vector of numeric variables to screen. When
|
method |
Outlier rule. |
z_cut |
Numeric cutoff for |
iqr_multiplier |
Numeric multiplier for |
p_cut |
Probability cutoff for |
Value
An object of class sframe_outlier_report with the method, screened
variables, a result table, flagged row numbers, and a reporting prompt.
Examples
demo <- sframe_demo_data()
outliers <- outlier_report(
demo$responses,
variables = c("dm_1", "dm_2", "sat_1"),
method = "zscore"
)
outliers$flagged_rows
Plot analysis-plan results
Description
Draws the charts that run_analysis_plan() attaches when called with
plots = TRUE. With which supplied, returns that single chart. With
which omitted, prints every attached chart in queue order and returns
the list invisibly. Regression diagnostic panels stay on the result's
diagnostic_plots element and are not drawn here.
Usage
## S3 method for class 'sframe_analysis_results'
plot(x, ..., which = NULL)
Arguments
x |
An |
... |
Ignored. |
which |
A research-question number or a plan block id selecting one chart, or NULL for all. |
Value
A ggplot2 object when which is supplied, otherwise an invisible
named list of ggplot2 objects keyed by plan block id.
Post-hoc and pairwise comparison report
Description
Post-hoc and pairwise comparison report
Usage
posthoc_report(
data,
method = c("anova", "kruskal_wallis", "chi_square", "cochran_q"),
outcome = NULL,
group = NULL,
table_vars = NULL,
measures = NULL,
correction = c("holm", "bonferroni", "BH")
)
Arguments
data |
A data.frame. |
method |
Comparison family. Supports |
outcome |
Outcome variable for group comparisons. |
group |
Grouping variable for group comparisons. |
table_vars |
Two categorical variables for chi-square residuals and pairwise proportion tests. |
measures |
Repeated binary measures for pairwise McNemar tests. |
correction |
Multiple-comparison correction. |
Value
An object of class sframe_posthoc_report.
Print an sf_branch object
Description
Print an sf_branch object
Usage
## S3 method for class 'sf_branch'
print(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
x, invisibly.
Examples
br <- sf_branch("q2", depends_on = "q1", operator = "==",
value = "yes", action = "show")
print(br)
Print an sf_check object
Description
Print an sf_check object
Usage
## S3 method for class 'sf_check'
print(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
x, invisibly.
Examples
ck <- sf_check("attn1", item_id = "q5", type = "attention",
pass_values = 3)
print(ck)
Print an sf_choices object
Description
Print an sf_choices object
Usage
## S3 method for class 'sf_choices'
print(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
x, invisibly.
Examples
cs <- sf_choices("agree5", 1:5,
c("Strongly disagree", "Disagree", "Neutral",
"Agree", "Strongly agree"))
print(cs)
Print an sf_item object
Description
Print an sf_item object
Usage
## S3 method for class 'sf_item'
print(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
x, invisibly.
Examples
it <- sf_item("q1", "How satisfied are you?", type = "likert",
choice_set = "agree5")
print(it)
Print an sf_model object
Description
Print an sf_model object
Usage
## S3 method for class 'sf_model'
print(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
x, invisibly.
Print an sf_scale object
Description
Print an sf_scale object
Usage
## S3 method for class 'sf_scale'
print(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
x, invisibly.
Examples
sc <- sf_scale("sat", "Satisfaction", items = c("q1", "q2", "q3"))
print(sc)
Print an sframe instrument object
Description
Displays a compact summary of an sframe instrument object, showing
the title, version, item count, scale count, and validation status.
Usage
## S3 method for class 'sframe'
print(x, ...)
Arguments
x |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
x, invisibly.
Examples
item <- sf_item("q1", "How satisfied are you?", type = "likert",
choice_set = "agree5")
instr <- sf_instrument("My Survey", components = list(item))
print(instr)
Generate a data quality report for survey responses
Description
Evaluates collected response data against the instrument specification and produces a structured quality report. The report covers attention check performance, completion time, straight-lining within scale blocks, item-level missingness, respondent-level missingness, and duplicate respondent IDs where supplied.
Usage
quality_report(
data,
instrument,
respondent_id = NULL,
submitted_at = NULL,
started_at = NULL,
time_min = NULL,
straightline_scales = TRUE,
missing_threshold = 0.2
)
Arguments
data |
A |
instrument |
An |
respondent_id |
Character or NULL. The column name holding unique respondent identifiers. Used for duplicate detection. |
submitted_at |
Character or NULL. The column name holding submission timestamps. Used for completion time analysis. |
started_at |
Character or NULL. The column name holding survey start
timestamps. When |
time_min |
Numeric or NULL. Minimum acceptable completion time in seconds. Respondents with a submission time below this threshold are flagged as speeders when timing data are available. |
straightline_scales |
Logical. Whether to check for straight-lining
within each defined scale block. Defaults to |
missing_threshold |
Numeric. The proportion of missing item responses
above which a respondent is flagged. Defaults to |
Details
Timing analysis is available when the data contain a submission timestamp
column and either an explicit started_at column or one of the recognised
defaults: started_at, start_time, started, or .started_at.
Value
An object of class sframe_quality_report, a named list with
elements: summary, attention, timing, straightline, missing,
and duplicates. Use print() for a formatted summary.
See Also
sf_check(), read_responses(), score_scales()
Examples
instr <- read_sframe(
system.file("extdata", "tourism_services_demo.sframe",
package = "surveyframe")
)
responses <- read_responses(
system.file("extdata", "tourism_services_responses.csv",
package = "surveyframe"),
instr,
respondent_id = "respondent_id",
submitted_at = "submitted_at",
meta_cols = "started_at"
)
qr <- quality_report(
responses,
instr,
respondent_id = "respondent_id",
submitted_at = "submitted_at",
started_at = "started_at",
straightline_scales = FALSE
)
print(qr)
Read and validate survey responses
Description
Loads survey response data and checks that it conforms to the instrument
specification. Column names in the response file must match item IDs defined
in the instrument. Non-item columns are allowed only when declared through
respondent_id, submitted_at, or meta_cols.
Usage
read_responses(
x,
instrument,
respondent_id = NULL,
submitted_at = NULL,
meta_cols = NULL,
strict = TRUE
)
Arguments
x |
A file path to a CSV file, a |
instrument |
An |
respondent_id |
Character or NULL. The name of the column containing unique respondent identifiers. If NULL, no respondent ID column is expected. |
submitted_at |
Character or NULL. The name of the column containing submission timestamps. |
meta_cols |
Character vector or NULL. Additional column names that are not item IDs but should be retained (for example, condition assignment or source URL). |
strict |
Logical. When |
Value
A data.frame with columns ordered as: metadata columns first, then
item columns in instrument order. Unrecognised columns are dropped when
strict = TRUE or appended with a warning when strict = FALSE.
See Also
quality_report(), score_scales()
Examples
responses <- read_responses(
x = system.file("extdata", "tourism_services_responses.csv",
package = "surveyframe"),
instrument = read_sframe(
system.file("extdata", "tourism_services_demo.sframe",
package = "surveyframe")
),
respondent_id = "respondent_id",
submitted_at = "submitted_at",
meta_cols = "started_at"
)
head(responses[, c("respondent_id", "visit_type", "dm_1")])
Read an instrument from a .sframe file
Description
Reads a .sframe JSON file and reconstructs an sframe instrument object.
The SHA-256 integrity hash is verified on load unless validate = FALSE.
Usage
read_sframe(path, validate = TRUE)
Arguments
path |
Character. The path to a |
validate |
Logical. Whether to validate the loaded instrument with
|
Value
An sframe object.
See Also
write_sframe(), validate_sframe()
Examples
instr <- read_sframe(
system.file("extdata", "tourism_services_demo.sframe",
package = "surveyframe")
)
print(instr)
Read survey responses from a Google Sheet
Description
Reads response data collected by the surveyframe Google Apps Script endpoint and returns a validated data frame ready for the surveyframe analysis pipeline.
Usage
read_sheet_responses(
sheet_id,
instrument,
sheet_name = "Responses",
respondent_id = "respondent_id",
submitted_at = "submitted_at",
meta_cols = NULL
)
Arguments
sheet_id |
Character. The Google Sheet ID or full URL. |
instrument |
An |
sheet_name |
Character. The name of the sheet tab holding responses.
Defaults to |
respondent_id |
Character or NULL. Column holding respondent IDs.
Defaults to |
submitted_at |
Character or NULL. Column holding submission
timestamps. Defaults to |
meta_cols |
Character vector or NULL. Additional sheet columns to
accept as metadata without a warning, for example bridge fields a host
application appends to each submission. |
Value
A data.frame validated against the instrument, ready for
quality_report(), score_scales(), and reliability_report().
See Also
export_google_sheet(), read_responses(), quality_report()
Examples
## Not run:
responses <- read_sheet_responses(
sheet_id = "your-sheet-id",
instrument = instr
)
qr <- quality_report(responses, instr, respondent_id = "respondent_id")
## End(Not run)
Compute reliability statistics for scored scales
Description
Produces Cronbach's alpha and McDonald's omega for each scale defined in the instrument, along with the number of items and sample size.
Usage
reliability_report(data, instrument, scales = NULL, alpha = TRUE, omega = TRUE)
Arguments
data |
A |
instrument |
An |
scales |
Character vector or NULL. A subset of scale IDs to analyse. When NULL (default), all scales in the instrument are included. |
alpha |
Logical. Whether to compute Cronbach's alpha. Defaults to
|
omega |
Logical. Whether to compute McDonald's omega. Defaults to
|
Value
An object of class sframe_reliability_report, a list with one
element per scale. Each element is a list of statistics and a summary
tibble.
See Also
Examples
if (requireNamespace("psych", quietly = TRUE)) {
demo <- sframe_demo_data()
rr <- reliability_report(demo$responses, demo$instrument, omega = FALSE)
print(rr)
}
Render a reproducible survey report
Description
Generates an HTML report that includes the instrument codebook, data quality summary, reliability diagnostics, and analysis-plan content. When Quarto and the bundled template are available, the report is rendered through Quarto. Otherwise, surveyframe writes an internal HTML fallback so the reporting workflow still runs on machines without Quarto.
Usage
render_report(
instrument,
data = NULL,
output_file = NULL,
output_path = NULL,
format = c("html", "pdf"),
include_quality = TRUE,
include_reliability = TRUE,
include_codebook = TRUE,
include_missing = TRUE,
include_descriptives = TRUE,
include_analysis = TRUE,
include_models = TRUE,
plot_palette = c("web", "print"),
interpretations = NULL
)
Arguments
instrument |
An |
data |
A |
output_file |
Character or NULL. The output file path. When NULL, a temporary file is written and its path returned. |
output_path |
Character or NULL. Alias for |
format |
Character. Output format: |
include_quality |
Logical. Whether to include the data quality report.
Requires |
include_reliability |
Logical. Whether to include reliability
diagnostics. Requires |
include_codebook |
Logical. Whether to include the instrument codebook.
Defaults to |
include_missing |
Logical. Whether to include the missing-data report.
Requires |
include_descriptives |
Logical. Whether to include descriptive
statistics. Requires |
include_analysis |
Logical. Whether to include analysis-plan results
when |
include_models |
Logical. Whether to include saved model JSON and
generated syntax blocks. Defaults to |
plot_palette |
One of |
interpretations |
Named list or NULL. Written interpretations keyed by analysis-plan block id, added after the results are known. When a block has an entry, its report section shows the pre-declared decision rule under a "Planned decision rule" label followed by the written text under an "Interpretation" label. Blocks without an entry render exactly as they do when this argument is NULL. Interpretations are report content only and are never written into the instrument. |
Value
The output file path, invisibly.
See Also
codebook_report(), quality_report(), reliability_report()
Examples
instr <- read_sframe(
system.file("extdata", "tourism_services_demo.sframe",
package = "surveyframe")
)
responses <- read_responses(
system.file("extdata", "tourism_services_responses.csv",
package = "surveyframe"),
instr,
respondent_id = "respondent_id",
submitted_at = "submitted_at",
meta_cols = "started_at"
)
old <- options(surveyframe.use_quarto = FALSE)
out <- tryCatch(
render_report(
instr,
data = responses,
output_file = tempfile(fileext = ".html"),
include_reliability = FALSE,
include_analysis = FALSE
),
finally = options(old)
)
file.exists(out)
Render analysis results to a formatted HTML report
Description
Generates a self-contained HTML report from the output of
run_analysis_plan(). Each section corresponds to one research question
and includes the APA-formatted statistical result, an interpretation space,
and a reference list.
Usage
render_results(
results = NULL,
instrument,
output_file = NULL,
output_path = NULL,
citation_format = c("apa", "ama", "vancouver"),
title = NULL,
interpretations = NULL
)
Arguments
results |
An |
instrument |
An |
output_file |
Character or NULL. Path to the output HTML file. When NULL, a temporary file is written and its path returned. |
output_path |
Character or NULL. Alias for |
citation_format |
Character. Reference format. One of |
title |
Character or NULL. Report title. Defaults to the instrument title with " – Results" appended. |
interpretations |
Named list or NULL. Written interpretations keyed by analysis-plan block id, added after the results are known. A block with an entry shows that text in its Interpretation section in place of the pre-declared prompt fallback. Blocks without an entry render exactly as they do when this argument is NULL. Interpretations are report content only and are never written into the instrument. |
Value
The output file path, invisibly.
See Also
run_analysis_plan(), render_report()
Examples
instr <- read_sframe(
system.file("extdata", "tourism_services_demo.sframe",
package = "surveyframe")
)
responses <- read_responses(
system.file("extdata", "tourism_services_responses.csv",
package = "surveyframe"),
instr,
respondent_id = "respondent_id",
submitted_at = "submitted_at",
meta_cols = "started_at"
)
results <- run_analysis_plan(responses, instr)
out <- render_results(results, instr,
output_file = tempfile(fileext = ".html"))
file.exists(out)
Render a survey from an instrument object
Description
Launches a Shiny survey with a welcome page, configurable header, all item types, branching logic, required-field enforcement, progress tracking, standard and conversational (one-question-at-a-time) display modes, and a customisable thank-you page. Responses can be persisted to CSV or passed to a callback.
Usage
render_survey(
instrument,
mode = c("shiny"),
title = NULL,
theme = NULL,
save_responses = c("none", "csv"),
output_path = NULL,
on_submit = NULL
)
Arguments
instrument |
An |
mode |
Character. Deployment mode. Currently |
title |
Character or NULL. Override for the survey title. |
theme |
Character or NULL. Hex colour for the survey theme. |
save_responses |
Character. |
output_path |
Character or NULL. CSV path when |
on_submit |
Function or NULL. Callback receiving the submitted row. |
Value
A shiny.appobj.
See Also
launch_studio(), read_responses()
Examples
cs <- sf_choices("ag5", 1:5,
c("Strongly disagree", "Disagree", "Neutral",
"Agree", "Strongly agree"))
item <- sf_item("sat_1", "How satisfied are you?",
type = "likert", choice_set = "ag5")
instr <- sf_instrument("My Survey", components = list(cs, item))
app <- render_survey(instr)
app <- render_survey(instr, save_responses = "csv", output_path = tempfile(fileext = ".csv"))
Run a pre-planned analysis from an instrument's analysis plan
Description
Executes every analysis block defined in the instrument's analysis_plan
slot against the supplied response data. Each block corresponds to one
research question defined during instrument design in the SurveyBuilder.
Results include APA-formatted statistics, effect sizes, interpretation
prompts, and reporting references.
Usage
run_analysis_plan(
data,
instrument,
scored = TRUE,
plots = FALSE,
plot_palette = c("web", "print")
)
Arguments
data |
A |
instrument |
An |
scored |
Logical. Whether to automatically score scales before running
the analysis. Defaults to |
plots |
Logical. When |
plot_palette |
One of |
Value
An object of class sframe_analysis_results, a list with one
element per analysis block. Each element contains the test result,
APA string, interpretation prompt, and reporting-reference metadata.
Inferential blocks also carry a $table data frame suitable for
knitr::kable(). Pass to render_results() to generate a formatted
report.
See Also
render_results(), read_sheet_responses()
Examples
instr <- read_sframe(
system.file("extdata", "tourism_services_demo.sframe",
package = "surveyframe")
)
responses <- read_responses(
system.file("extdata", "tourism_services_responses.csv",
package = "surveyframe"),
instr,
respondent_id = "respondent_id",
submitted_at = "submitted_at",
meta_cols = "started_at"
)
results <- run_analysis_plan(responses, instr)
print(results)
Sample-size and power planning helper
Description
Sample-size and power planning helper
Usage
sample_size_plan(
type = c("proportion", "mean", "correlation", "t_test", "anova", "regression", "sem"),
margin_error = NULL,
sd = NULL,
p = 0.5,
r = NULL,
alpha = 0.05,
power = 0.8,
groups = 2L,
predictors = NULL
)
Arguments
type |
Planning target: |
margin_error |
Margin of error for mean/proportion planning. |
sd |
Standard deviation for mean planning. |
p |
Expected proportion. |
r |
Expected correlation. |
alpha |
Significance level. |
power |
Desired power. |
groups |
Number of groups for ANOVA/t-test planning. |
predictors |
Number of predictors for regression planning. |
Value
A list of planning estimates and warnings.
Score defined scales from survey responses
Description
Applies scale scoring rules from the instrument to response data. Handles reverse coding, optional weighted composite score computation, and minimum valid item thresholds. Returns a data frame with one scored column per scale.
Usage
score_scales(data, instrument, keep_items = TRUE, keep_meta = TRUE)
Arguments
data |
A |
instrument |
An |
keep_items |
Logical. Whether to retain individual item columns in the
output. Defaults to |
keep_meta |
Logical. Whether to retain non-item columns (metadata) in
the output. Defaults to |
Value
A data.frame with scored scale columns appended. Scale columns are
named using the scale id.
See Also
sf_scale(), reliability_report()
Examples
cs <- sf_choices("ag5", 1:5,
c("Strongly disagree", "Disagree", "Neutral",
"Agree", "Strongly agree"))
i1 <- sf_item("sat_1", "Item 1", type = "likert",
choice_set = "ag5", scale_id = "sat")
i2 <- sf_item("sat_2", "Item 2", type = "likert",
choice_set = "ag5", scale_id = "sat")
i3 <- sf_item("sat_3", "Item 3 (reverse)", type = "likert",
choice_set = "ag5", scale_id = "sat", reverse = TRUE)
scale <- sf_scale("sat", "Satisfaction",
items = c("sat_1", "sat_2", "sat_3"), min_valid = 2L)
instr <- sf_instrument("Demo", components = list(cs, i1, i2, i3, scale))
responses <- data.frame(
sat_1 = c(4, 5, 3),
sat_2 = c(4, 4, 3),
sat_3 = c(2, 1, 3),
stringsAsFactors = FALSE
)
scored <- score_scales(responses, instr)
scored$sat
Generate lavaan CB-SEM syntax
Description
Generate lavaan CB-SEM syntax
Usage
sem_lavaan_syntax(model, instrument = NULL, standardised = TRUE)
Arguments
model |
An |
instrument |
Optional |
standardised |
Logical. Adds a standardised-estimates fitting note. |
Value
A lavaan syntax string.
Generate seminr PLS-SEM syntax
Description
Generate seminr PLS-SEM syntax
Usage
seminr_syntax(model, data_name = "data", nboot = NULL, seed = 123)
Arguments
model |
An |
data_name |
Name of the data object in generated R code. |
nboot |
Number of bootstrap samples. |
seed |
Random seed for bootstrap syntax. |
Value
An R syntax string for seminr.
Define a branching rule
Description
Creates a single-condition branching rule that shows or hides a survey item depending on the value of a preceding item. Only single-condition rules are supported. Multi-condition AND/OR logic is planned for a later release.
Usage
sf_branch(
item_id,
depends_on,
operator = c("==", "!=", "%in%", ">", ">=", "<", "<="),
value,
action = c("show", "hide")
)
Arguments
item_id |
Character. The |
depends_on |
Character. The |
operator |
Character. The comparison operator. One of |
value |
The value to compare against the response to |
action |
Character. What to do when the condition is met. Either
|
Value
An object of class sf_branch (a named list).
See Also
sf_instrument(), validate_sframe()
Examples
# Show an open-text follow-up only when the respondent selects "Other"
rule <- sf_branch(
item_id = "gender_other",
depends_on = "gender",
operator = "==",
value = "other",
action = "show"
)
Define a design-time survey check
Description
Specifies an attention, instructional, or trap check item at instrument
design time. The check is stored in the instrument object and evaluated
against collected response data by quality_report(). This function only
defines the check. Evaluation happens later in quality_report().
Usage
sf_check(
id,
item_id,
type = c("attention", "instructional", "trap"),
pass_values = NULL,
fail_action = c("flag", "exclude"),
label = NULL,
notes = NULL
)
Arguments
id |
Character. A unique identifier for this check. |
item_id |
Character. The |
type |
Character. The check type. One of:
|
pass_values |
Vector or NULL. The response value or values that
constitute a pass. For |
fail_action |
Character. What |
label |
Character or NULL. An optional human-readable label for the check, used in the quality report. |
notes |
Character or NULL. Optional free-text notes about the purpose or rationale of this check. |
Value
An object of class sf_check (a named list).
See Also
sf_item(), sf_instrument(), quality_report()
Examples
# An attention check: respondent must select 4
chk <- sf_check(
id = "attn_1",
item_id = "attention_check_q",
type = "attention",
pass_values = 4,
fail_action = "flag",
label = "Attention check 1"
)
Define a reusable choice set
Description
Creates a named set of response options that can be referenced by one or
more items. Defining choices once and referencing them by id keeps the
instrument consistent and reduces the risk of label mismatches across items
that share the same response format.
Usage
sf_choices(id, values, labels, allow_other = FALSE, randomise = FALSE)
Arguments
id |
Character. A unique identifier for this choice set. Referenced in
the |
values |
Character or numeric vector. The stored values corresponding
to each response option. Must have the same length as |
labels |
Character vector. The display labels shown to respondents.
Must have the same length as |
allow_other |
Logical. Whether to append an open-text "Other" option
at the end of the choice list. Defaults to |
randomise |
Logical. Whether to randomise the display order of options
at render time. Defaults to |
Value
An object of class sf_choices (a named list).
See Also
Examples
# A five-point agreement scale
agree5 <- sf_choices(
id = "agree5",
values = 1:5,
labels = c("Strongly disagree", "Disagree", "Neutral",
"Agree", "Strongly agree")
)
# A yes/no set
yn <- sf_choices(
id = "yn",
values = c("yes", "no"),
labels = c("Yes", "No")
)
Define a latent or composite construct
Description
Define a latent or composite construct
Usage
sf_construct(
id,
label = NULL,
items = character(0),
mode = c("reflective", "composite", "formative", "single_item"),
weights = NULL
)
Arguments
id |
Construct identifier. Must start with a letter and contain only
letters, numbers, and |
label |
Human-readable construct label. |
items |
Character vector of indicator item IDs. |
mode |
Measurement mode. One of |
weights |
Optional indicator weights for later PLS-SEM planning. |
Value
An object of class sf_construct.
Define a covariance between constructs
Description
Define a covariance between constructs
Usage
sf_covariance(from, to, label = NULL)
Arguments
from |
First construct ID. |
to |
Second construct ID. |
label |
Optional label. |
Value
An object of class sf_covariance.
Define an indirect effect path
Description
Define an indirect effect path
Usage
sf_indirect(from, through, to, label = NULL)
Arguments
from |
Source construct ID. |
through |
Character vector of mediator construct IDs. |
to |
Target construct ID. |
label |
Optional effect label. |
Value
An object of class sf_indirect.
Create a survey instrument object
Description
Assembles a survey instrument from its component objects. This is
the top-level constructor for the sframe class. All other constructors
(sf_item(), sf_choices(), sf_scale(), sf_branch(), sf_check())
produce components that are passed into this function via components.
Usage
sf_instrument(
title,
version = "0.1.0",
description = NULL,
authors = NULL,
languages = "en",
components = list(),
render = NULL,
analysis_plan = list(),
models = list()
)
Arguments
title |
Character. The title of the survey instrument. |
version |
Character. A semantic version string. Defaults to |
description |
Character or NULL. A brief description of the instrument and its intended population or purpose. |
authors |
Character vector or NULL. Author names, used in codebooks and reports. |
languages |
Character vector. Language codes for the instrument.
Defaults to |
components |
List. A list of component objects created by the
constructor family: |
render |
List or NULL. Optional rendering hints passed to
|
analysis_plan |
List. Optional pre-planned analysis blocks created in the HTML SurveyBuilder Analyse mode. |
models |
List. Optional model specifications created with |
Value
An object of class sframe with slots meta, items, choices,
scales, branching, checks, analysis_plan, models, and render.
See Also
sf_item(), sf_choices(), sf_scale(), sf_branch(),
sf_check(), validate_sframe(), write_sframe()
Examples
choices <- sf_choices("agree5", 1:5,
c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
visitor_cs <- sf_choices("visitor", c("new", "returning"),
c("New visitor", "Returning visitor"))
item1 <- sf_item("sat_1", "The service met my expectations.",
type = "likert", choice_set = "agree5",
scale_id = "sat", required = TRUE)
item2 <- sf_item("sat_2", "I would recommend this service.",
type = "likert", choice_set = "agree5",
scale_id = "sat", required = TRUE)
item3 <- sf_item("visitor_type", "I am a",
type = "single_choice", choice_set = "visitor")
scale <- sf_scale("sat", "Satisfaction", items = c("sat_1", "sat_2"))
# The analysis_plan binds each research question to a statistical method
# and the variable roles it needs. Declare it before any data arrive.
plan <- list(
list(
id = "RQ1",
research_question = "Do new and returning visitors differ in satisfaction?",
family = "group_comparison",
method = "mann_whitney",
roles = list(group = "visitor_type", outcome = "sat"),
options = list(alpha = 0.05)
)
)
instr <- sf_instrument(
title = "Service Quality Survey",
version = "1.0.0",
components = list(choices, visitor_cs, item1, item2, item3, scale),
analysis_plan = plan
)
print(instr)
length(instr$analysis_plan)
Define a survey item
Description
Creates a single survey item object for inclusion in an sframe instrument.
Items are the atomic units of a survey instrument. Every item must have a
unique id within the instrument it is added to.
Usage
sf_item(
id,
label,
type = c("likert", "single_choice", "multiple_choice", "numeric", "text", "textarea",
"date", "matrix", "slider", "ranking", "rating", "section_break", "text_block"),
required = FALSE,
choice_set = NULL,
scale_id = NULL,
reverse = FALSE,
help = NULL,
placeholder = NULL,
matrix_items = NULL,
slider_min = NULL,
slider_max = NULL,
slider_step = NULL,
rating_max = NULL,
rating_icon = NULL,
date_min = NULL,
date_max = NULL,
section_intro = NULL,
page = NULL
)
Arguments
id |
Character. A unique identifier for this item. Used as the column
name in response data. Must contain only letters, numbers, and |
label |
Character. The question text or content displayed to the respondent. |
type |
Character. The response type. One of |
required |
Logical. Whether the respondent must answer this item. |
choice_set |
Character or NULL. The |
scale_id |
Character or NULL. The |
reverse |
Logical. Whether this item is reverse-coded within its scale. |
help |
Character or NULL. Help text displayed beneath the question. |
placeholder |
Character or NULL. Placeholder text for text inputs. |
matrix_items |
Character vector or NULL. Row labels for |
slider_min |
Numeric or NULL. Minimum value for |
slider_max |
Numeric or NULL. Maximum value for |
slider_step |
Numeric or NULL. Step size for |
rating_max |
Integer or NULL. Maximum rating for |
rating_icon |
Character or NULL. Icon type: |
date_min |
Character or Date or NULL. Earliest selectable date for
|
date_max |
Character or Date or NULL. Latest selectable date for
|
section_intro |
Character or NULL. Intro text for |
page |
Integer or NULL. Page number for multi-page surveys. |
Value
An object of class sf_item (a named list).
See Also
sf_instrument(), sf_choices(), sf_scale()
Examples
item <- sf_item(
id = "sat_overall", label = "Overall, how satisfied are you?",
type = "likert", required = TRUE, choice_set = "agree5",
scale_id = "satisfaction"
)
sec <- sf_item("sec_1", "Demographic Information", type = "section_break",
section_intro = "Please answer the following questions.")
Create a surveyframe model specification
Description
Create a surveyframe model specification
Usage
sf_model(
id,
label = NULL,
type = c("efa", "cfa", "cb_sem", "pls_sem"),
engine = NULL,
constructs = list(),
paths = list(),
covariances = list(),
indirect = list(),
options = list()
)
Arguments
id |
Model identifier. |
label |
Human-readable model label. |
type |
Model type. One of |
engine |
Optional engine name. Defaults to |
constructs |
List of |
paths |
List of |
covariances |
List of |
indirect |
List of |
options |
List of model options, such as |
Value
An object of class sf_model.
Define a structural path between constructs
Description
Define a structural path between constructs
Usage
sf_path(from, to, label = NULL)
Arguments
from |
Source construct ID. |
to |
Target construct ID. |
label |
Optional lavaan label for the path. |
Value
An object of class sf_path.
Define a scored scale
Description
Creates a scale definition that groups items and specifies how composite
scores are computed. The scale carries scoring rules used by score_scales()
and measurement structure used by reliability_report(), item_report(),
and cfa_syntax().
Usage
sf_scale(
id,
label,
items,
method = c("mean", "sum"),
min_valid = NULL,
reverse_items = NULL,
weights = NULL
)
Arguments
id |
Character. A unique identifier for this scale. Referenced in the
|
label |
Character. A human-readable name for the scale, used in reports and codebooks. |
items |
Character vector. The |
method |
Character. Scoring method. Either |
min_valid |
Integer or NULL. The minimum number of non-missing items
required to compute a score for a respondent. When |
reverse_items |
Character vector or NULL. A subset of |
weights |
Numeric vector or NULL. Item weights for weighted scoring.
Must have the same length as |
Value
An object of class sf_scale (a named list).
See Also
sf_item(), score_scales(), reliability_report()
Examples
sat_scale <- sf_scale(
id = "satisfaction",
label = "Customer Satisfaction",
items = c("sat_overall", "sat_speed", "sat_quality"),
method = "mean",
min_valid = 2,
reverse_items = NULL
)
Abort with a branching error
Description
Abort with a branching error
Usage
sframe_abort_branching(message, item_id = NULL, ...)
Arguments
message |
Character. The error message. |
item_id |
Character or NULL. The item ID involved in the broken rule. |
... |
Additional named fields passed to |
Abort with an import error
Description
Abort with an import error
Usage
sframe_abort_import(message, path = NULL, ...)
Arguments
message |
Character. The error message. |
path |
Character or NULL. The file path that failed to import. |
... |
Additional named fields passed to |
Abort with a validation error
Description
Abort with a validation error
Usage
sframe_abort_validation(message, instrument_title = NULL, ...)
Arguments
message |
Character. The error message. |
instrument_title |
Character or NULL. Title of the instrument being validated, included in the condition metadata when supplied. |
... |
Additional named fields passed to |
Create an empty SurveyStudio builder state
Description
Create an empty SurveyStudio builder state
Usage
sframe_builder_empty_state()
Value
A list containing empty metadata, choice, item, scale, branching, and check collections suitable for SurveyStudio.
Convert an instrument into a SurveyStudio builder state
Description
Convert an instrument into a SurveyStudio builder state
Usage
sframe_builder_state_from_instrument(instrument = NULL)
Arguments
instrument |
An |
Value
A builder state list. Component classes are restored so the state can be edited or validated by SurveyStudio.
Validate a SurveyStudio draft state
Description
Validate a SurveyStudio draft state
Usage
sframe_builder_validate_draft(
meta,
choices = list(),
items = list(),
scales = list(),
branching = list(),
checks = list(),
analysis_plan = list(),
models = list(),
render = list()
)
Arguments
meta |
List of instrument metadata. |
choices, items, scales, branching, checks |
Lists of draft components. |
analysis_plan |
List of draft analysis-plan blocks. |
models |
List of draft model specifications. |
render |
List of rendering settings (welcome, header/logo, thankyou, theme) carried from the loaded instrument so previews and exports match. |
Value
A list with valid, problems, and instrument.
Enrich a codebook's items table for display
Description
Replaces items_table's choice_set id with the choice set's actual
response options ("1 = Strongly disagree; 2 = Disagree; ...") and its
scale_id with the scale's label, so each row of the printed codebook is
self-contained. codebook_report() itself keeps the raw ids (for joining
items_table to choices_table/scales_table programmatically); this
is for the rendered document, where a reader should not need to
cross-reference a separate table just to see what "1" means on a scale
shared by many items.
Usage
sframe_codebook_items_display(cb)
Arguments
cb |
An |
Value
A data.frame, cb$items_table with choice_set and scale_id
replaced by display text.
See Also
Load bundled surveyframe demo data
Description
Loads the bundled tourism-services .sframe instrument and simulated
response dataset used in package examples and statistical workflow demos.
Usage
sframe_demo_data()
Value
A list with instrument, responses, instrument_path, and
responses_path.
Diverging stacked bar for a single Likert item (base graphics)
Description
Base graphics only (no ggplot2 dependency), so it draws in the report's
distributions section regardless of whether ggplot2 is installed,
including from the Quarto report template, which runs in its own
library(surveyframe) session and cannot see unexported functions.
counts is a named numeric vector in scale order (names are the response
labels, e.g. "Strongly disagree" .. "Strongly agree"), not sorted
alphabetically or by frequency. The middle category of an odd-length
scale is treated as neutral and split evenly across the zero line; an
even-length scale has no neutral category. This is the standard
survey-report convention (Pew Research, SurveyMonkey) for visualising an
ordered agree/disagree scale, and reads in one glance which way opinion
leans, unlike a plain frequency bar.
Usage
sframe_draw_likert_diverging(
counts,
theme_color = "#16B3B1",
palette = c("web", "print")
)
Arguments
counts |
Named numeric vector of response counts, in scale order. |
theme_color |
Character. Hex colour for the "agree" pole. |
palette |
One of |
Details
Kept horizontal deliberately: this is the one chart in the package where the horizontal orientation is the domain convention, not an accident, and a vertical diverging stack is materially harder to read for this specific shape (see the file-level note in the roxygen docs of the ggplot2 equivalents above). Position (left of zero vs right of zero) carries the primary signal either way, so it also satisfies "do not rely on colour alone" regardless of palette. In print mode, the two poles are further distinguished by a diagonal hatch on the "disagree" side, not colour tone alone.
Value
Invisibly NULL; called for its plotting side effect on the
current graphics device.
See Also
Mosaic plot for a two-way categorical result
Description
Base-graphics mosaic plot (via graphics::mosaicplot()), matching the
existing base-graphics precedent in this file
(sframe_draw_likert_diverging()) so it renders without ggplot2. An
alternative view of the same crosstab data
sframe_plot_crosstab() renders as a grouped bar; use whichever reads
better for the table's shape (mosaic scales better to unbalanced group
sizes).
Usage
sframe_draw_mosaic(result, palette = c("web", "print"))
Arguments
result |
A |
palette |
One of |
Value
Invisibly NULL; called for its plotting side effect on the
current graphics device.
See Also
sframe_plot_crosstab()
Load bundled input-types demo data
Description
Loads the bundled .sframe instrument and simulated response dataset that
cover all main survey input types supported by surveyframe.
Usage
sframe_input_types_demo_data()
Value
A list with instrument, responses, instrument_path, and
responses_path.
Group a scale's Likert items for a combined diverging chart
Description
Identifies which of an instrument's scales are eligible for one grouped
diverging chart across their member items (sframe_plot_likert_scale()),
the same way a "matrix" question's rows are grouped
(sframe_plot_likert_matrix()): every member item is "likert" type and
all share one choice set. Scales that mix response scales, that resolve
to fewer than 2 qualifying items, or whose choice set cannot be found are
left out and fall back to one chart per item in the report's Response
distributions section.
Usage
sframe_likert_scale_groups(instrument)
Arguments
instrument |
An |
Value
A named list, one entry per eligible scale (named by scale id),
each a list with scale_id, title (the scale's label), items (the
member item objects, in scale order), and choice_set (the shared
choice set object). Empty list if no scale qualifies.
See Also
sframe_plot_likert_scale(), sf_scale()
Correlation matrix heatmap
Description
Computes and plots a full pairwise correlation matrix, independent of
run_analysis_plan()'s pairwise correlation_pearson/_spearman/
_kendall runners (which plot one variable pair at a time via
sframe_plot_correlation()). Useful directly, and as the visual
companion to validity_report()'s discriminant-validity checks.
Usage
sframe_plot_correlation_matrix(
data,
vars,
method = "pearson",
palette = c("web", "print")
)
Arguments
data |
A data frame of survey responses. |
vars |
Character vector of column names to correlate. |
method |
One of |
palette |
One of |
Value
A ggplot2 object.
See Also
Distribution shape by variable, standardised
Description
One violin per variable in a descriptives_report() table, built from
the underlying response data rather than from the summary skewness and
kurtosis numbers, so the reader sees the actual shape (asymmetry,
multimodality, tails) instead of reading it off a bar height. Each
variable is standardised (z-scored) before plotting so variables on
different original scales (a 5-point Likert item next to a 0-100 slider)
share one comparable y-axis; standardising is a linear transform and does
not change skewness. Each violin's subtitle-free panel keeps the
variable's skewness value in its axis label. Grouped descriptives_report()
output (one row per variable per split_by group) is faceted by group.
Usage
sframe_plot_descriptives(x, data, palette = c("web", "print"))
Arguments
x |
An |
data |
The same data.frame passed to |
palette |
One of |
Value
A ggplot2 object, or NULL if none of the report's variables have
enough data to draw.
See Also
Loadings heatmap from a fitted EFA solution
Description
Loadings heatmap from a fitted EFA solution
Usage
sframe_plot_efa_loadings(x, palette = c("web", "print"))
Arguments
x |
An |
palette |
One of |
Value
A ggplot2 object.
See Also
Scree plot from an EFA readiness report
Description
Plots the parallel-analysis eigenvalues from efa_report() (both the
observed factor-analysis eigenvalues and the simulated comparison line),
with the suggested factor count marked.
Usage
sframe_plot_efa_scree(x, palette = c("web", "print"))
Arguments
x |
An |
palette |
One of |
Value
A ggplot2 object.
See Also
Group-comparison boxplot
Description
Boxplot with jittered points, shared across every runner whose result
carries vars = c(group_column, outcome_column): t_test_ind,
mann_whitney, kruskal_wallis, and anova_one. One function instead of
four, since the underlying comparison (an outcome split by a grouping
factor) and the data shape needed to plot it are identical across all
four tests; only the inferential statistic differs.
Usage
sframe_plot_group_comparison(result, data, palette = c("web", "print"))
Arguments
result |
A result list from one of the four runners above, with
|
data |
The response data frame the result was computed from. |
palette |
One of |
Value
A ggplot2 object, or NULL if the columns are missing, fewer
than two groups remain after removing missing values, or ggplot2 is
unavailable.
See Also
Item distribution chart, ggplot2 equivalent of the dashboard/studio panel
Description
Shared by launch_dashboard() (inst/shiny/dashboard/app.R) and the
SurveyStudio dashboard tab (inst/shiny/app.R), which otherwise
duplicated this base-graphics chart. Callers fall back to their own base
graphics when this returns NULL (ggplot2 not installed, unsupported
item type, or no data), so the dashboard keeps working without ggplot2.
Usage
sframe_plot_item_chart(
item,
col_data,
choice_set = NULL,
palette = c("web", "print")
)
Arguments
item |
A list with at least |
col_data |
The response column for this item. |
choice_set |
A list with |
palette |
One of |
Value
A ggplot2 object, or NULL if this item type/data is unsupported.
Grouped diverging chart for a Likert matrix question
Description
A matrix question asks several rows against one shared response scale
(a "grid" of Likert items). Plotting each row as its own separate
sframe_draw_likert_diverging() chart loses the grouping the question
was designed with, so this draws every row as one diverging bar inside a
single chart, sharing one x scale and one legend, the standard way a
Likert matrix is reported (compare a typical multi-item satisfaction
grid). Same diverging-stack convention as the single-item chart: the
middle category of an odd-length scale is neutral and split evenly
across the zero line, and colour saturation increases toward each pole.
Usage
sframe_plot_likert_matrix(item, data, choice_set, palette = c("web", "print"))
Arguments
item |
A |
data |
The response data.frame, with one expanded
|
choice_set |
The item's choice set object ( |
palette |
One of |
Value
A ggplot2 object, or NULL if no row has response data.
See Also
sframe_draw_likert_diverging()
Grouped diverging chart for a scale's Likert items
Description
Several separate Likert items that make up one sf_scale() (unlike a
"matrix" item's rows, which are one question) are, by default, each
reported as their own single-item diverging chart. That scatters a
related batch of items (a satisfaction scale's 2-3 items, say) across
several charts instead of showing them the way a Likert matrix or a
typical multi-item satisfaction grid is reported: one grouped chart, one
diverging bar per item, sharing an x scale and a legend. Applies only
when every item in the scale shares the same choice set; scales that mix
response scales fall back to one chart per item.
Usage
sframe_plot_likert_scale(
items,
data,
choice_set,
title,
palette = c("web", "print")
)
Arguments
items |
A list of |
data |
The response data.frame, with one column per item id. |
choice_set |
The shared choice set object ( |
title |
Chart title, typically the scale's label. |
palette |
One of |
Value
A ggplot2 object, or NULL if no item has response data.
See Also
sframe_plot_likert_matrix(), sf_scale()
Missing-data report plot: missingness rate by item
Description
Missing-data report plot: missingness rate by item
Usage
sframe_plot_missingness(x, palette = c("web", "print"))
Arguments
x |
An |
palette |
One of |
Value
A ggplot2 object. When no item has missing values, this is a short "no missing responses" message rather than an empty bar chart.
See Also
Paired-comparison slope plot
Description
One line per respondent connecting their two paired values, shared by
t_test_pair and wilcoxon_pair (both carry vars = c(x_column, y_column) on the same respondents). The standard visual for a paired
design: it shows the direction and consistency of individual change,
which a plain bar-of-means would hide.
Usage
sframe_plot_paired_comparison(result, data, palette = c("web", "print"))
Arguments
result |
A result list from |
data |
The response data frame the result was computed from. |
palette |
One of |
Value
A ggplot2 object, or NULL if fewer than two complete pairs
remain, or ggplot2 is unavailable.
See Also
Quality report plot: straight-lining flag rate by scale
Description
Quality report plot: straight-lining flag rate by scale
Usage
sframe_plot_quality(x, palette = c("web", "print"))
Arguments
x |
An |
palette |
One of |
Value
A ggplot2 object.
See Also
Regression diagnostic plots for a regression_linear result
Description
The four standard diagnostic panels (residuals vs fitted, normal Q-Q,
scale-location, residuals vs leverage), built from the plain data frame
run_analysis_plan() attaches to a regression_linear result rather than
the lm object itself, so the result stays JSON-serialisable.
Usage
sframe_plot_regression_diagnostics(result, palette = c("web", "print"))
Arguments
result |
A |
palette |
One of |
Value
A named list of four ggplot2 objects (residuals_fitted, qq,
scale_location, leverage), or NULL if diagnostics are unavailable.
See Also
Reliability plot: alpha and omega by scale
Description
Reliability plot: alpha and omega by scale
Usage
sframe_plot_reliability(x, palette = c("web", "print"))
Arguments
x |
An |
palette |
One of |
Value
A ggplot2 object.
See Also
Scale score distribution chart, ggplot2 equivalent of the dashboard panel
Description
Same sharing rationale as sframe_plot_item_chart().
Usage
sframe_plot_scale_chart(scores, label, palette = c("web", "print"))
Arguments
scores |
Numeric vector of scale scores (already averaged/summed). |
label |
Character. Scale label, used as the x-axis title. |
palette |
One of |
Value
A ggplot2 object, or NULL if ggplot2 is unavailable or scores
is empty.
Validity report plot: composite reliability and AVE by construct
Description
Validity report plot: composite reliability and AVE by construct
Usage
sframe_plot_validity(x, palette = c("web", "print"))
Arguments
x |
An |
palette |
One of |
Value
A ggplot2 object.
See Also
Raw-variable distribution panels: histogram, boxplot, and Q-Q
Description
Unlike sframe_plot_descriptives(), which summarises skewness and
kurtosis across the variables in a descriptives_report() table, this
operates on one variable's raw values directly (the report table only
stores summary statistics, not the underlying vector), matching the
pattern sframe_plot_correlation_matrix() already uses for
report-independent, data-driven plots.
Usage
sframe_plot_variable_distribution(data, variable, palette = c("web", "print"))
Arguments
data |
A data frame of survey responses. |
variable |
Character. Column name of the variable to plot. |
palette |
One of |
Value
A named list of three ggplot2 objects (histogram, boxplot,
qq), or NULL if fewer than two complete values remain.
See Also
descriptives_report(), sframe_plot_descriptives()
Warn about missing data
Description
Warn about missing data
Usage
sframe_warn_missing(message, item_id = NULL, rate = NULL, ...)
Arguments
message |
Character. The warning message. |
item_id |
Character or NULL. The item ID with missing data. |
rate |
Numeric or NULL. The observed missing rate. |
... |
Additional named fields passed to |
Warn about a data quality issue
Description
Warn about a data quality issue
Usage
sframe_warn_quality(message, respondent_ids = NULL, ...)
Arguments
message |
Character. The warning message. |
respondent_ids |
Character vector or NULL. IDs of affected respondents. |
... |
Additional named fields passed to |
Warn about a scoring issue
Description
Warn about a scoring issue
Usage
sframe_warn_scoring(message, scale_id = NULL, ...)
Arguments
message |
Character. The warning message. |
scale_id |
Character or NULL. The scale ID affected. |
... |
Additional named fields passed to |
Summarise an sf_branch object
Description
Summarise an sf_branch object
Usage
## S3 method for class 'sf_branch'
summary(object, ...)
Arguments
object |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
object, invisibly.
Summarise an sf_check object
Description
Summarise an sf_check object
Usage
## S3 method for class 'sf_check'
summary(object, ...)
Arguments
object |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
object, invisibly.
Summarise an sf_choices object
Description
Summarise an sf_choices object
Usage
## S3 method for class 'sf_choices'
summary(object, ...)
Arguments
object |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
object, invisibly.
Summarise an sf_item object
Description
Summarise an sf_item object
Usage
## S3 method for class 'sf_item'
summary(object, ...)
Arguments
object |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
object, invisibly.
Summarise an sf_model object
Description
Summarise an sf_model object
Usage
## S3 method for class 'sf_model'
summary(object, ...)
Arguments
object |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
object, invisibly.
Summarise an sf_scale object
Description
Summarise an sf_scale object
Usage
## S3 method for class 'sf_scale'
summary(object, ...)
Arguments
object |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
object, invisibly.
Summarise an sframe instrument object
Description
Prints a structured summary of an sframe object including metadata,
item type counts, scale definitions, branching rules, and check
specifications.
Usage
## S3 method for class 'sframe'
summary(object, ...)
Arguments
object |
An object of class |
... |
Ignored. Present for S3 consistency. |
Value
object, invisibly.
Examples
item <- sf_item("q1", "How satisfied are you?", type = "likert",
choice_set = "agree5")
instr <- sf_instrument("My Survey", components = list(item))
summary(instr)
Shiny module server for an embedded survey
Description
Renders the survey instrument and collects the respondent's answers.
Returns a reactive that holds NULL until the form is submitted, then
returns the response as a named list (one element per visible item).
Usage
survey_module_server(id, instrument, on_submit = NULL)
Arguments
id |
A character string matching the |
instrument |
An |
on_submit |
Optional function of one argument. Called immediately
after submission with the response list. Useful for writing to a
database or sending an email without waiting for an
|
Value
A reactive that returns NULL before submission and the
response list after.
See Also
Examples
# See survey_module_ui() for a complete example.
Shiny module UI for an embedded survey
Description
Places a survey rendered by surveyframe inside a larger Shiny application.
Pair with survey_module_server() in the server function. The module
renders the full instrument including welcome page, all item types,
branching logic, required-field validation, and a thank-you screen.
Usage
survey_module_ui(id, width = "100%")
Arguments
id |
A character string. The module namespace ID, passed identically
to |
width |
Character. CSS width for the survey card. Defaults to
|
Value
A shiny.tag object.
See Also
survey_module_server(), launch_studio(),
export_static_survey()
Examples
## Not run:
# Minimal embedding example:
library(shiny)
library(surveyframe)
cs <- sf_choices("ag5", 1:5, c("SD", "D", "N", "A", "SA"))
item <- sf_item("q1", "Rate your experience.", type = "likert",
choice_set = "ag5", required = TRUE)
instr <- sf_instrument("Quick Survey", components = list(cs, item))
ui <- fluidPage(
survey_module_ui("demo"),
verbatimTextOutput("result")
)
server <- function(input, output, session) {
resp <- survey_module_server("demo", instrument = instr)
output$result <- renderPrint({
req(resp())
resp()
})
}
shinyApp(ui, server)
## End(Not run)
surveyframe brand theme for ggplot2
Description
A theme_classic()-based ggplot2 theme (visible axis lines, no floating
panel), verified against WCAG 2.2 contrast minimums: 4.5:1 for text,
3:1 for non-text graphical objects. Apply it to any ggplot object,
including the plots returned by run_analysis_plan() when
plots = TRUE.
Usage
theme_surveyframe(
base_size = 12,
base_family = "",
palette = c("web", "print")
)
Arguments
base_size |
Numeric. Base font size in points. Defaults to 12. |
base_family |
Character. Base font family. Defaults to |
palette |
One of |
Value
A ggplot2 theme object.
See Also
Examples
library(ggplot2)
ggplot(mtcars, aes(wt, mpg)) +
geom_point(colour = "#0E9694") +
theme_surveyframe()
Validate a surveyframe model specification
Description
Checks model IDs, construct IDs, indicators, structural path endpoints, duplicate paths, indirect paths, and engine/type compatibility.
Usage
validate_model(model, instrument = NULL, strict = TRUE)
Arguments
model |
An |
instrument |
Optional |
strict |
Logical. When |
Value
The model invisibly when valid and strict = TRUE, otherwise a
validation result list.
Validate an instrument object
Description
Checks the internal consistency of an sframe instrument object and
reports all detected problems. Validation is performed automatically by
write_sframe() and optionally by read_sframe(). It can also be run
independently at any point during instrument construction.
Usage
validate_sframe(instrument, strict = TRUE)
Arguments
instrument |
An |
strict |
Logical. When |
Details
The following checks are performed:
Duplicate item IDs
Invalid item IDs
Duplicate choice-set IDs
Duplicate scale IDs
Items with missing labels
Items referencing a missing
choice_setin the instrumentItems referencing a missing
scale_idin the instrumentItems marked
reverse = TRUEwithout ascale_idChoice sets referenced by items but not present in the instrument
Scale
itemsvectors containing IDs not present in the instrumentBranching rules referencing item IDs not present in the instrument
Attention checks referencing item IDs not present in the instrument
Analysis plan roles referencing missing variables or models
Model specifications referencing missing indicators or constructs
Value
When strict = TRUE and the instrument is valid, the instrument
is returned invisibly with meta$validated set to TRUE. When
strict = FALSE, a named list with elements valid (logical) and
problems (character vector) is returned.
See Also
sf_instrument(), write_sframe()
Examples
# Build a minimal valid instrument and validate it
cs <- sf_choices("ag5", 1:5,
c("Strongly disagree", "Disagree", "Neutral",
"Agree", "Strongly agree"))
item <- sf_item("sat_1", "The service met my expectations.",
type = "likert", choice_set = "ag5", scale_id = "sat")
scale <- sf_scale("sat", "Satisfaction", items = "sat_1")
instr <- sf_instrument("Demo Survey", components = list(cs, item, scale))
# Non-strict: returns a list without stopping
result <- validate_sframe(instr, strict = FALSE)
result$valid
result$problems
# Strict: returns instrument invisibly when valid
validated <- validate_sframe(instr, strict = TRUE)
isTRUE(validated$meta$validated)
Validity report for construct models
Description
Validity report for construct models
Usage
validity_report(loadings, construct_scores = NULL, items_by_construct = NULL)
Arguments
loadings |
A data.frame with columns |
construct_scores |
Optional data.frame of construct scores for Fornell-Larcker and inter-construct correlations. |
items_by_construct |
Optional named list, one element per construct,
each a data.frame of that construct's item-level responses. When
supplied, |
Value
An object of class sframe_validity_report.
Write an instrument to a .sframe file
Description
Serialises an sframe instrument object to a UTF-8 JSON file with a
SHA-256 integrity hash. The instrument is validated before writing unless
the object already carries a valid status. The hash is computed over the
full serialised content with the hash.value field set to an empty string.
Usage
write_sframe(instrument, path, pretty = TRUE, overwrite = FALSE)
Arguments
instrument |
An |
path |
Character. The file path to write to. The |
pretty |
Logical. Whether to write formatted JSON with indentation.
Defaults to |
overwrite |
Logical. Whether to overwrite an existing file. Defaults
to |
Value
The file path, invisibly.
See Also
read_sframe(), validate_sframe()
Examples
instr <- read_sframe(
system.file("extdata", "tourism_services_demo.sframe",
package = "surveyframe")
)
out <- write_sframe(instr, tempfile(fileext = ".sframe"))
file.exists(out)