| Title: | 'Shiny' Interface for Complex Survey Data Analysis |
|---|---|
| Description: | Provides a 'Shiny'-based interactive interface for the analysis of complex survey data. The package supports data import from multiple file formats, construction and diagnosis of complex survey designs with stratification, clustering, and sampling weights, as well as estimation of means, totals, proportions, associated standard errors, confidence intervals, and design effects. The multilingual interface facilitates the analysis and visualization of survey results without requiring specialized programming knowledge. |
| Authors: | Stalyn Guerrero Gómez [aut, cre] |
| Maintainer: | Stalyn Guerrero Gómez <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 1.0.1 |
| Built: | 2026-07-06 16:27:17 UTC |
| Source: | https://github.com/cran/complexr |
Shiny server for complexr
app_server(input, output, session)app_server(input, output, session)
input |
Shiny input |
output |
Shiny output |
session |
Shiny session |
Shiny UI for complexr
app_ui()app_ui()
A Shiny UI object.
Constructs a tbl_svy design object from survey microdata by encoding
the sampling structure required for design-based inference: adjusted weights
, stratification variable , primary sampling units (PSUs)
, and an optional finite population correction (FPC).
as_survey_design_tbl( data, weight, strata = NULL, cluster = NULL, fpc = NULL, nest = TRUE, check_psu = TRUE )as_survey_design_tbl( data, weight, strata = NULL, cluster = NULL, fpc = NULL, nest = TRUE, check_psu = TRUE )
data |
A tibble containing survey microdata with one row per
sampled unit |
weight |
Character string. Name of the column holding the adjusted
sampling weights |
strata |
Optional character string. Name of the column identifying
the stratum |
cluster |
Optional character string. Name of the column identifying
the PSU |
fpc |
Optional character string. Name of the column holding the
finite population correction value for each unit, used to reduce
variance estimates when the sampling fraction |
nest |
Logical. Whether PSU labels are nested within strata, i.e.
the same PSU code may appear in different strata. Default is |
check_psu |
Logical. If |
Let be the finite population and
the sample. For each unit , the
first-order inclusion probability is
and the basic design weight is
. The adjusted weight stored in
weight incorporates any non-response or calibration corrections
applied after data collection.
The function wraps survey::svydesign() and converts the result to
a srvyr object via srvyr::as_survey().
Supported design configurations
| Configuration | Arguments supplied |
| Simple random sampling (SRS) | weight only |
| Stratified | weight + strata |
| Single-stage cluster | weight + cluster |
| Stratified multistage | weight + strata +
cluster |
| Any of the above with FPC | add fpc
|
Design weights and inclusion probabilities
For a stratified multistage design with strata and
PSUs in stratum , the Horvitz–Thompson (HT)
estimator of the population total is:
where are the adjusted weights of unit
in PSU of stratum . The resulting tbl_svy
object encodes this structure so that all subsequent calls to
estimate_survey use the correct design-based variance
estimator .
Lonely PSU handling
When a stratum contains only one PSU (),
the within-stratum variance cannot be estimated by Taylor linearization.
The function automatically sets
options(survey.lonely.psu = "adjust") so that variance is
approximated by centering the PSU total at the stratum mean, following
the conservative recommendation of Cochran (1977).
Finite population correction
When the sampling fraction is non-negligible
(typically ), supply fpc to reduce variance estimates
by the factor .
A tbl_svy object (class from srvyr) compatible with
srvyr and survey functions. The object carries a
"design_vars" attribute that records weight, strata,
cluster, fpc and nest for downstream diagnostics.
Horvitz, D. G. & Thompson, D. J. (1952). A generalization of sampling without replacement from a finite universe. Journal of the American Statistical Association, 47(260), 663–685. doi:10.1080/01621459.1952.10483446
Cochran, W. G. (1977). Sampling Techniques (3rd ed.). Wiley.
Sarndal, C.-E., Swensson, B. & Wretman, J. (1992). Model Assisted Survey Sampling. Springer. doi:10.1007/978-1-4612-4378-6
Lumley, T. (2010). Complex Surveys: A Guide to Analysis Using R. Wiley. doi:10.1002/9780470580066
describe_survey_design,
estimate_survey,
svydesign,
as_survey
data <- generate_example_data(n_upm = 30) # Stratified multistage design: weight = w_k, strata = h, cluster = alpha design <- as_survey_design_tbl( data, weight = "weight", strata = "strata", cluster = "upm" ) # Cluster design without stratification (H = 1) design2 <- as_survey_design_tbl( data, weight = "weight", cluster = "upm" ) # Weights-only design (SRS approximation, d_k = w_k) design3 <- as_survey_design_tbl( data, weight = "weight" )data <- generate_example_data(n_upm = 30) # Stratified multistage design: weight = w_k, strata = h, cluster = alpha design <- as_survey_design_tbl( data, weight = "weight", strata = "strata", cluster = "upm" ) # Cluster design without stratification (H = 1) design2 <- as_survey_design_tbl( data, weight = "weight", cluster = "upm" ) # Weights-only design (SRS approximation, d_k = w_k) design3 <- as_survey_design_tbl( data, weight = "weight" )
Returns a one-row tibble of design diagnostics: sample size ,
number of strata , total number of PSUs ,
and summary statistics of the adjusted weights including their
coefficient of variation , which is an
indicator of weight variability and its effect on variance inflation.
describe_survey_design(design)describe_survey_design(design)
design |
A |
A tibble with one row and the following columns:
n_obsTotal sample size .
n_strataNumber of strata
(NA if no stratification variable was supplied).
n_clustersTotal number of PSUs
(NA if no cluster variable was supplied).
weight_min.
weight_max.
weight_meanUnweighted mean of the adjusted weights
, where
.
weight_cvCoefficient of variation of the weights
. Large values () indicate
high weight variability, which can substantially inflate the
design effect .
as_survey_design_tbl, estimate_survey
data <- generate_example_data(30) design <- as_survey_design_tbl( data, weight = "weight", strata = "strata", cluster = "upm" ) describe_survey_design(design)data <- generate_example_data(30) design <- as_survey_design_tbl( data, weight = "weight", strata = "strata", cluster = "upm" ) describe_survey_design(design)
Computes design-based point estimates and their associated uncertainty
measures for complex survey data. The function operates on objects of class
tbl_svy and implements five estimators grounded in the
Horvitz–Thompson (HT) framework: weighted mean , population
total , proportion , ratio ,
and quantile .
estimate_survey( design, variable = NULL, estimator = c("mean", "total", "prop", "ratio", "quantile"), by = NULL, na_rm = TRUE, conf_level = 0.95, numerator = NULL, denominator = NULL, ratio_num_level = NULL, ratio_den_level = NULL, probs = c(0.25, 0.5, 0.75) )estimate_survey( design, variable = NULL, estimator = c("mean", "total", "prop", "ratio", "quantile"), by = NULL, na_rm = TRUE, conf_level = 0.95, numerator = NULL, denominator = NULL, ratio_num_level = NULL, ratio_den_level = NULL, probs = c(0.25, 0.5, 0.75) )
design |
A |
variable |
Character string with the name of the target variable
|
estimator |
Character string specifying the estimator. One of
|
by |
Optional character vector naming domain variables that define
subpopulations |
na_rm |
Logical. Whether to remove |
conf_level |
Numeric in |
numerator |
Character string with the name of the numerator variable
|
denominator |
Character string with the name of the denominator variable
|
ratio_num_level |
Character. Category of |
ratio_den_level |
Character. Category of |
probs |
Numeric vector of probabilities in |
Let be the finite population and
the selected sample. For each unit , is
the basic design weight (inverse of the first-order inclusion
probability ), and is the adjusted weight
after non-response or calibration corrections.
All estimators account for stratification, clustering and unequal weights.
Variance is estimated by Taylor linearization via the survey and
srvyr packages, and the design effect
is reported for mean, total and
proportion estimators. Domain estimation (argument by) is supported
for all estimators; variance is computed over the full sample to
avoid subsetting bias.
Mean
The weighted mean is the HT ratio estimator:
where is the estimated population
size. Its variance is estimated by Taylor linearization (Sarndal et al.,
1992):
Total
The HT estimator of the population total is (Horvitz & Thompson, 1952):
With adjusted weights and a stratified multistage design
( strata, PSUs per stratum ,
observations per PSU):
Proportion
For a binary variable , the estimated proportion is:
For a categorical variable with categories , the
proportion of category is ,
where is the weighted count of units with .
Variance is approximated by Taylor linearization (Heeringa et al., 2017):
Ratio
The ratio estimator of two population totals is (Cochran, 1977):
Variance is estimated by first-order Taylor linearization:
When variables are categorical, indicator variables are constructed for
the specified levels before calling survey::svyratio().
The deff column is NA for ratio estimates.
Quantile
Quantiles are derived from the weighted empirical CDF (Woodruff, 1952):
Confidence intervals use the Woodruff linearization method, which maps the problem to the cumulative proportion scale:
The deff column is NA for quantile estimates.
Design effect
For estimators that support it, the output column deff contains
(Kish, 1965):
Domain estimation
When by is supplied, estimation is performed within each
subpopulation defined by the combination of domain variable
levels. The domain mean estimator is:
Variance is computed over the full sample , preserving the design
structure and avoiding subsetting bias (Lumley, 2010).
Confidence intervals
Intervals are constructed under asymptotic normality as:
A tibble with the following columns, plus one column per domain variable
(if by is supplied):
variableName of the target variable .
estimatorType of estimator ("mean", "total",
etc.).
estimatePoint estimate .
seStandard error
.
cvCoefficient of variation
.
deffDesign effect
(mean, total, proportion only;
NA for ratio and quantile).
lciLower confidence bound.
uciUpper confidence bound.
qualityPrecision label derived from the :
"Very high precision" (),
"High precision" (–),
"Acceptable precision" (–),
"Use with caution" (–), or
"Low precision" ().
Horvitz, D. G. & Thompson, D. J. (1952). A generalization of sampling without replacement from a finite universe. Journal of the American Statistical Association, 47(260), 663–685. doi:10.1080/01621459.1952.10483446
Cochran, W. G. (1977). Sampling Techniques (3rd ed.). Wiley.
Woodruff, R. S. (1952). Confidence intervals for medians and other position measures. Journal of the American Statistical Association, 47(260), 635–646. doi:10.1080/01621459.1952.10483443
Kish, L. (1965). Survey Sampling. Wiley.
Sarndal, C.-E., Swensson, B. & Wretman, J. (1992). Model Assisted Survey Sampling. Springer. doi:10.1007/978-1-4612-4378-6
Lumley, T. (2010). Complex Surveys: A Guide to Analysis Using R. Wiley. doi:10.1002/9780470580066
Heeringa, S. G., West, B. T. & Berglund, P. A. (2017). Applied Survey Data Analysis (2nd ed.). CRC Press. doi:10.1201/9781315153278
survey_mean,
survey_total,
svyratio,
svyquantile,
as_survey_design_tbl
# --------------------------------------------------------- # Generate example data and build a stratified multistage # design: weight = w_k, strata = h, cluster = alpha # --------------------------------------------------------- data <- generate_example_data(n_upm = 30, seed = 123) design <- srvyr::as_survey_design( data, ids = upm, strata = strata, weights = weight ) # --------------------------------------------------------- # Mean -- bar{y}_w with DEFF and 95 % CI # --------------------------------------------------------- estimate_survey( design, variable = "ingreso_pc", estimator = "mean" ) # Domain mean bar{y}_{w,d} by region estimate_survey( design, variable = "ingreso_pc", estimator = "mean", by = "region" ) # --------------------------------------------------------- # Total -- hat{Y}_{HT} with DEFF # --------------------------------------------------------- estimate_survey( design, variable = "ingreso_pc", estimator = "total" ) # --------------------------------------------------------- # Proportion -- hat{p} = hat{N}_1 / hat{N}_w # --------------------------------------------------------- estimate_survey( design, variable = "pobre", estimator = "prop" ) # Multinomial proportion hat{p}_c = hat{N}_c / hat{N}_w estimate_survey( design, variable = "empleo", estimator = "prop" ) # --------------------------------------------------------- # Ratio -- hat{R} = hat{Y}_w / hat{X}_w # --------------------------------------------------------- estimate_survey( design, estimator = "ratio", numerator = "ingreso_pc", denominator = "gasto_pc" ) # Ratio with domains estimate_survey( design, estimator = "ratio", numerator = "ingreso_pc", denominator = "gasto_pc", by = "region" ) # Categorical / Categorical: hat{N}_{Formal} / hat{N}_{Informal} estimate_survey( design, estimator = "ratio", numerator = "empleo", denominator = "empleo", ratio_num_level = "Formal", ratio_den_level = "Informal" ) # --------------------------------------------------------- # Quantile -- hat{q}_p via Woodruff linearization # --------------------------------------------------------- estimate_survey( design, variable = "ingreso_pc", estimator = "quantile", probs = c(0.25, 0.5, 0.75) )# --------------------------------------------------------- # Generate example data and build a stratified multistage # design: weight = w_k, strata = h, cluster = alpha # --------------------------------------------------------- data <- generate_example_data(n_upm = 30, seed = 123) design <- srvyr::as_survey_design( data, ids = upm, strata = strata, weights = weight ) # --------------------------------------------------------- # Mean -- bar{y}_w with DEFF and 95 % CI # --------------------------------------------------------- estimate_survey( design, variable = "ingreso_pc", estimator = "mean" ) # Domain mean bar{y}_{w,d} by region estimate_survey( design, variable = "ingreso_pc", estimator = "mean", by = "region" ) # --------------------------------------------------------- # Total -- hat{Y}_{HT} with DEFF # --------------------------------------------------------- estimate_survey( design, variable = "ingreso_pc", estimator = "total" ) # --------------------------------------------------------- # Proportion -- hat{p} = hat{N}_1 / hat{N}_w # --------------------------------------------------------- estimate_survey( design, variable = "pobre", estimator = "prop" ) # Multinomial proportion hat{p}_c = hat{N}_c / hat{N}_w estimate_survey( design, variable = "empleo", estimator = "prop" ) # --------------------------------------------------------- # Ratio -- hat{R} = hat{Y}_w / hat{X}_w # --------------------------------------------------------- estimate_survey( design, estimator = "ratio", numerator = "ingreso_pc", denominator = "gasto_pc" ) # Ratio with domains estimate_survey( design, estimator = "ratio", numerator = "ingreso_pc", denominator = "gasto_pc", by = "region" ) # Categorical / Categorical: hat{N}_{Formal} / hat{N}_{Informal} estimate_survey( design, estimator = "ratio", numerator = "empleo", denominator = "empleo", ratio_num_level = "Formal", ratio_den_level = "Informal" ) # --------------------------------------------------------- # Quantile -- hat{q}_p via Woodruff linearization # --------------------------------------------------------- estimate_survey( design, variable = "ingreso_pc", estimator = "quantile", probs = c(0.25, 0.5, 0.75) )
Formats survey estimation outputs by ensuring required metrics are present (CV, confidence intervals) and applying rounding.
format_results_table(res, digits = 2)format_results_table(res, digits = 2)
res |
A data.frame or tibble with estimation results. |
digits |
Integer. Number of decimal places. |
A tibble with formatted results.
res <- data.frame(estimate = c(0.45, 0.30), se = c(0.02, 0.015)) format_results_table(res)res <- data.frame(estimate = c(0.45, 0.30), se = c(0.02, 0.015)) format_results_table(res)
Generates a synthetic dataset representing a complex survey design with a three-level hierarchical structure: primary sampling units (PSUs), households, and individuals. The function ensures internal consistency of weights, cluster sizes, and derived variables, making it suitable for testing survey estimators, calibration methods, and small area estimation workflows.
generate_example_data(n_upm = 200, seed = 123)generate_example_data(n_upm = 200, seed = 123)
n_upm |
Integer. Number of primary sampling units (PSUs). |
seed |
Integer. Random seed for reproducibility. |
Sampling structure
The simulated data follows a hierarchical design:
PSU (UPM): each PSU belongs to a stratum and contains a random number of households (between 5 and 15).
Households: each household has a sampling weight and a fixed area (urban/rural).
Individuals: observations are generated at the individual level.
Weights
Sampling weights are defined at the household level and are constant for all individuals within the same household:
Income generation
Household income is generated with hierarchical random effects:
where:
is the PSU-level effect
is the household-level effect
Per capita income is then defined as:
where is the household size.
Education and income correlation
Education is assigned at the individual level conditional on age. A household-level education effect is derived from the maximum education level within the household and used to adjust household income:
where is a multiplicative factor depending on household
education.
Consistency constraints
The simulation enforces:
All individuals in a household share the same area
Individuals younger than 5 years have no education (NA)
Per capita income is constant within households
Each PSU contains at most 15 households
Variables
The dataset includes:
Design variables: strata, upm, hogar_id,
persona_id, weight
Domains: region, sexo, area
Demographics: edad, educacion, empleo
Welfare indicators: ingreso_pc, gasto_pc, pobre
Auxiliary variable with missingness: ingreso2
A tibble at the individual level with hierarchical identifiers and survey variables.
data <- generate_example_data(n_upm = 50) validate_simulation(data) # --------------------------------------------------------- # Example: build survey design # --------------------------------------------------------- # design <- as_survey_design_tbl( # data, # weight = "weight", # strata = "strata", # cluster = "upm" # )data <- generate_example_data(n_upm = 50) validate_simulation(data) # --------------------------------------------------------- # Example: build survey design # --------------------------------------------------------- # design <- as_survey_design_tbl( # data, # weight = "weight", # strata = "strata", # cluster = "upm" # )
Reads a JSON translation file from the package's inst/ directory and
returns it as a nested list suitable for use with i18n_t.
i18n_load(lang, path = "app/www/i18n")i18n_load(lang, path = "app/www/i18n")
lang |
Character. Language code, e.g. |
path |
Character. Path inside |
A named list with the translation dictionary.
dict <- i18n_load("en") i18n_t(dict, "mod_datos.title")dict <- i18n_load("en") i18n_t(dict, "mod_datos.title")
Resolves a dot-separated key path in a nested translation list returned by
i18n_load. Returns the key itself when the path is not found,
so the interface degrades gracefully on missing translations.
i18n_t(dict, key)i18n_t(dict, key)
dict |
List. A translation dictionary returned by |
key |
Character. A dot-separated path to the translation string, e.g.
|
A character string with the translated text, or key when the
path does not exist.
dict <- i18n_load("en") i18n_t(dict, "mod_datos.title") i18n_t(dict, "nonexistent.key") # returns "nonexistent.key"dict <- i18n_load("en") i18n_t(dict, "mod_datos.title") i18n_t(dict, "nonexistent.key") # returns "nonexistent.key"
Adds or transforms variables in survey microdata using a named list
of formulas. Each definition must be a one-sided formula of the form
~ expression, evaluated within the data context.
mutate_survey_data(data, definitions, overwrite = TRUE)mutate_survey_data(data, definitions, overwrite = TRUE)
data |
A tibble with survey microdata. |
definitions |
Named list of formulas defining new variables. |
overwrite |
Logical. If FALSE, prevents overwriting existing variables. |
A tibble with new variables added or modified.
data <- tibble::tibble( ingreso = c(100, 200), miembros = c(2, 4) ) mutate_survey_data( data, list( ingreso_pc = ~ ingreso / miembros ) )data <- tibble::tibble( ingreso = c(100, 200), miembros = c(2, 4) ) mutate_survey_data( data, list( ingreso_pc = ~ ingreso / miembros ) )
Plot survey estimates as bar chart
plot_results_bar(results)plot_results_bar(results)
results |
Tibble returned by estimate_survey(). |
A ggplot object.
res <- data.frame( region = c("North", "South", "East"), estimate = c(0.45, 0.30, 0.55), lci = c(0.40, 0.25, 0.50), uci = c(0.50, 0.35, 0.60), estimator = "prop" ) plot_results_bar(res)res <- data.frame( region = c("North", "South", "East"), estimate = c(0.45, 0.30, 0.55), lci = c(0.40, 0.25, 0.50), uci = c(0.50, 0.35, 0.60), estimator = "prop" ) plot_results_bar(res)
Reads microdata commonly used in official statistics and survey analysis from a local file path. The function returns a tibble and attaches source metadata as attributes, facilitating traceability and reproducibility.
read_survey_data( path, col_types = NULL, guess_max = 10000, encoding = "UTF-8", sheet = 1 )read_survey_data( path, col_types = NULL, guess_max = 10000, encoding = "UTF-8", sheet = 1 )
path |
Character. File path to the dataset. |
col_types |
Optional. Passed to |
guess_max |
Integer. Maximum rows used for type guessing (CSV/TSV only). |
encoding |
Character. File encoding (CSV/TSV only).
Default |
sheet |
Integer or character. Sheet to read for Excel files.
Default |
Supported formats:
.csv — comma-separated values (readr)
.tsv, .txt — tab-separated values (readr)
.xlsx — Excel 2007+ (readxl)
.xls — Excel 97-2003 (readxl)
.sav — SPSS (haven)
.por — SPSS portable (haven)
.dta — Stata (haven)
.sas7bdat — SAS data (haven)
.xpt — SAS transport (haven)
.rds — R serialized object (base R)
A tibble with attributes:
source_path: normalized file path
source_format: file extension
n_rows: number of rows
n_cols: number of columns
csv_path <- system.file("extdata", "simulated_survey_data.csv", package = "complexr") df <- read_survey_data(csv_path) attr(df, "source_format") rds_path <- system.file("extdata", "simulated_survey_data.rds", package = "complexr") df2 <- read_survey_data(rds_path) attr(df2, "source_format")csv_path <- system.file("extdata", "simulated_survey_data.csv", package = "complexr") df <- read_survey_data(csv_path) attr(df, "source_format") rds_path <- system.file("extdata", "simulated_survey_data.rds", package = "complexr") df2 <- read_survey_data(rds_path) attr(df2, "source_format")
Launches the Shiny app bundled within the package in the default browser.
run_app()run_app()
Called for its side effect: opens the Shiny application. Returns invisibly when the app is stopped.
if (interactive()) { run_app() }if (interactive()) { run_app() }
Performs a set of structural and consistency checks on a dataset generated
by generate_example_data(). The function verifies household-level
invariants (area, weights, per capita income), demographic rules,
and PSU size constraints.
validate_simulation(data, strict = FALSE)validate_simulation(data, strict = FALSE)
data |
A tibble or data.frame at individual level. |
strict |
Logical. If TRUE, stops execution when any validation fails. |
A tibble with validation results (one row per check).
data <- generate_example_data(n_upm = 20, seed = 123) validate_simulation(data)data <- generate_example_data(n_upm = 20, seed = 123) validate_simulation(data)