| Type: | Package |
| Title: | Ex Post Survey Data Harmonization |
| Version: | 0.2.9 |
| Date: | 2026-11-29 |
| Maintainer: | Daniel Antal <daniel.antal@dataobservatory.eu> |
| Description: | Assist in reproducible retrospective (ex-post) harmonization of data, particularly individual level survey data, by providing tools for organizing metadata, standardizing the coding of variables, and variable names and value labels, including missing values, and documenting the data transformations, with the help of comprehensive s3 classes. |
| License: | GPL-3 |
| URL: | https://retroharmonize.dataobservatory.eu/ |
| BugReports: | https://github.com/dataobservatory-eu/retroharmonize/issues |
| Depends: | R (≥ 3.5.0) |
| Imports: | cli, dataset, dplyr (≥ 1.0.0), fs, haven, here, labelled, magrittr, purrr, rlang, snakecase, stats, stringr, tibble, tidyr, tidyselect, utils, vctrs |
| Suggests: | covr, ggplot2, knitr, markdown, png, rmarkdown, pillar, spelling, statcodelists, testthat (≥ 3.0.0) |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| Language: | en-US |
| Config/roxygen2/version: | 8.1.1 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-29 14:50:05 UTC; DanielAntal |
| Author: | Daniel Antal |
| Repository: | CRAN |
| Date/Publication: | 2026-11-29 15:10:02 UTC |
retroharmonize: Ex Post Survey Data Harmonization
Description
Assist in reproducible retrospective (ex-post) harmonization of data, particularly individual level survey data, by providing tools for organizing metadata, standardizing the coding of variables, and variable names and value labels, including missing values, and documenting the data transformations, with the help of comprehensive s3 classes.
Author(s)
Maintainer: Daniel Antal daniel.antal@dataobservatory.eu (ORCID)
Authors:
Daniel Antal daniel.antal@dataobservatory.eu (ORCID)
Other contributors:
Marta Kolczynska mkolczynska@gmail.com (ORCID) [contributor]
See Also
Useful links:
Report bugs at https://github.com/dataobservatory-eu/retroharmonize/issues
Pipe operator
Description
See magrittr::%>% for details.
Usage
lhs %>% rhs
Convert a labelled vector to a labelled survey vector
Description
Convert a haven-labelled vector while preserving its variable label, value labels and missing value definitions.
Usage
as_labelled_spss_survey(x, id)
Arguments
x |
A vector inheriting from 'haven_labelled'. |
id |
The survey identifier. |
Value
A labelled_spss_survey vector.
See Also
Other type conversion functions:
labelled_spss_survey_coercion
Collect value labels from survey metadata
Description
Extract unique valid or user-defined missing value labels from survey metadata.
Usage
collect_val_labels(metadata)
collect_na_labels(metadata)
Arguments
metadata |
A metadata data frame created by [metadata_create()]. |
Details
'collect_val_labels()' collects labels from the 'valid_labels' column of the metadata.
'collect_na_labels()' collects labels from the 'na_labels' column of the metadata.
Duplicate labels are removed, preserving their first occurrence.
Value
A character vector of unique value labels. If no labels are found, an empty character vector is returned.
See Also
Other harmonization functions:
create_codebook(),
crosswalk_surveys(),
harmonize_na_values(),
harmonize_survey_values(),
harmonize_values(),
harmonize_var_names(),
is.crosswalk_table(),
label_normalize()
Examples
test_survey <- read_rds(
file = system.file(
"examples",
"ZA7576.rds",
package = "retroharmonize"
),
id = "test"
)
example_metadata <- metadata_create(survey_list = test_survey)
collect_val_labels(metadata = example_metadata)
collect_na_labels(metadata = example_metadata)
Concatenate compatible labelled vectors
Description
Concatenate two labelled vectors with compatible classes, value labels and missing value definitions.
Usage
concatenate(x, y)
Arguments
x |
A labelled vector. |
y |
A labelled vector of the same class as 'x'. |
Details
Value code-label associations and missing value definitions must be equivalent. Their ordering may differ.
If variable labels differ, the label of 'x' takes precedence and a warning is issued. If only one variable label is available, that label is retained.
Survey identifiers and compatible survey-specific metadata are retained.
Value
A concatenated labelled vector.
Examples
x <- haven::labelled_spss(
c(1, 2, 99),
labels = c(yes = 1, no = 2, missing = 99),
na_values = 99,
label = "Survey question"
)
y <- haven::labelled_spss(
c(2, 1),
labels = c(yes = 1, no = 2, missing = 99),
na_values = 99,
label = "Survey question"
)
concatenate(x, y)
Create a survey codebook
Description
Expand survey metadata into a long-format codebook of value labels.
Usage
create_codebook(metadata = NULL, survey = NULL)
codebook_waves_create(waves)
codebook_surveys_create(survey_list)
Arguments
metadata |
A metadata table created by |
survey |
A survey object of class |
waves |
Deprecated alias for 'survey_list'. |
survey_list |
A list of 'survey' or 'survey_df' objects. |
Details
create_codebook() returns a tidy data frame describing labelled
survey variables and their associated value labels. Each row
corresponds to a value label, classified as valid or missing.
Unlabelled numeric and character variables are excluded.
If both metadata and survey are supplied, survey takes
precedence.
For multiple surveys, use codebook_surveys_create().
Value
A data frame with one row per value label, including:
Survey identifiers (
id,filename).Original variable names and labels.
Original value codes and labels, represented as character vectors.
Label range (
"valid"or"missing").Summary counts of value labels.
Additional user-defined metadata columns are preserved.
See Also
metadata_create(), codebook_surveys_create()
Other metadata functions:
metadata_create(),
metadata_survey_create()
Other harmonization functions:
collect_val_labels(),
crosswalk_surveys(),
harmonize_na_values(),
harmonize_survey_values(),
harmonize_values(),
harmonize_var_names(),
is.crosswalk_table(),
label_normalize()
Examples
survey <- read_rds(
system.file("examples", "ZA7576.rds", package = "retroharmonize")
)
cb <- create_codebook(survey = survey)
head(cb)
examples_dir <- system.file("examples", package = "retroharmonize")
survey_files <- dir(
examples_dir,
pattern = "\\.rds$",
full.names = TRUE
)
example_surveys <- read_surveys(survey_paths = survey_files)
head(codebook_surveys_create(example_surveys))
Crosswalk and harmonize surveys
Description
Harmonize one or more surveys using a crosswalk table that defines how variable names, value labels, numeric codes, and variable classes should be aligned across surveys.
Usage
crosswalk_surveys(
crosswalk_table,
survey_list = NULL,
survey_paths = NULL,
import_path = NULL,
na_values = NULL
)
crosswalk(survey_list, crosswalk_table, na_values = NULL)
Arguments
crosswalk_table |
A crosswalk table created with [crosswalk_table_create()] or a data frame containing at least the columns 'id', 'var_name_orig', and 'var_name_target'. If the columns 'val_label_orig' and 'val_label_target' are present, value labels are harmonized. If 'val_numeric_orig' and 'val_numeric_target' are present, numeric codes are harmonized. If 'class_target' is present, variables are coerced to the specified target class ('"factor"', '"numeric"', or '"character"') using [as_factor()], [as_numeric()], or [as_character()]. |
survey_list |
A list of survey objects to be harmonized. |
survey_paths |
Optional character vector of file paths to surveys. Used when surveys must be read from disk before harmonization. |
import_path |
Optional base directory used to resolve 'survey_paths'. This is primarily intended for workflows where surveys are stored outside the current working directory. |
na_values |
Optional named vector defining numeric codes to be treated as missing values. Names correspond to missing-value labels. |
Details
A crosswalk table can be created with [crosswalk_table_create()] or supplied manually as a data frame. At a minimum, the table must contain columns 'id', 'var_name_orig', and 'var_name_target'. Additional columns enable harmonization of value labels, numeric codes, missing values, and variable classes.
Value
'crosswalk_surveys()' returns a list of harmonized survey data frames.
'crosswalk()' returns a single data frame combining the harmonized surveys by row.
See Also
[crosswalk_table_create()] to create a crosswalk table, [harmonize_survey_variables()] for lower-level variable harmonization.
Other harmonization functions:
collect_val_labels(),
create_codebook(),
harmonize_na_values(),
harmonize_survey_values(),
harmonize_values(),
harmonize_var_names(),
is.crosswalk_table(),
label_normalize()
Examples
## Not run:
examples_dir <- system.file("examples", package = "retroharmonize")
survey_files <- dir(examples_dir, pattern = "\\.rds$")
surveys <- read_surveys(
file.path(examples_dir, survey_files)
)
metadata <- metadata_create(survey_list = surveys)
crosswalk_table <- crosswalk_table_create(metadata)
harmonized <- crosswalk_surveys(
crosswalk_table = crosswalk_table,
survey_list = surveys
)
## End(Not run)
Document survey item provenance
Description
Document the current and historical coding, labels, missing values, and survey provenance of a harmonized survey variable.
Usage
document_survey_item(x)
Arguments
x |
A 'labelled_spss_survey' vector originating from a single survey or concatenated from multiple surveys. |
Value
A named list containing:
current and historical value coding,
variable labels,
valid and missing value definitions,
original variable names,
survey identifiers.
See Also
Other documentation functions:
document_surveys()
Examples
var1 <- labelled::labelled_spss(
x = c(1, 0, 1, 1, 0, 8, 9),
labels = c(
"TRUST" = 1,
"NOT TRUST" = 0,
"DON'T KNOW" = 8,
"INAP. HERE" = 9
),
na_values = c(8, 9)
)
var2 <- labelled::labelled_spss(
x = c(2, 2, 8, 9, 1, 1),
labels = c(
"Tend to trust" = 1,
"Tend not to trust" = 2,
"DK" = 8,
"Inap" = 9
),
na_values = c(8, 9)
)
harmonization <- list(
from = c(
"^tend\\sto|^trust",
"^tend\\snot|not\\strust",
"^dk|^don",
"^inap"
),
to = c(
"trust",
"not_trust",
"do_not_know",
"inap"
),
numeric_values = c(1, 0, 99997, 99999)
)
missing_values <- c(
"do_not_know" = 99997,
"inap" = 99999
)
h1 <- harmonize_values(
x = var1,
harmonize_label = "Do you trust the European Union?",
harmonize_labels = harmonization,
na_values = missing_values,
id = "survey1"
)
h2 <- harmonize_values(
x = var2,
harmonize_label = "Do you trust the European Union?",
harmonize_labels = harmonization,
na_values = missing_values,
id = "survey2"
)
h3 <- concatenate(h1, h2)
document_survey_item(h3)
Document survey lists
Description
Summarize the identifiers, dimensions, memory requirements and file attributes of survey datasets.
Usage
document_surveys(survey_list = NULL, survey_paths = NULL, .f = NULL)
document_waves(waves)
Arguments
survey_list |
A list of objects of class [survey()] or [survey_df()]. |
survey_paths |
A character vector of paths to survey files. Defaults to 'NULL'. |
.f |
An optional function used to import survey files. If 'NULL', the import function is determined by [read_survey()]. See [read_rds()], [read_spss()] and [read_dta()] for supported import functions. |
waves |
A list of objects of class [survey()] or [survey_df()]. |
Details
Surveys can be documented either from objects already loaded into memory or directly from source files.
When 'survey_list' is supplied, the function documents the survey identifiers, filenames, dimensions and memory requirements without reading the source files again.
When 'survey_paths' is supplied, the function reads each file sequentially and additionally documents its file size, last access time and last modification time.
If both arguments are supplied, 'survey_list' takes precedence.
'document_waves()' is deprecated. Use 'document_surveys()' instead.
Value
A tibble with one row per survey and the following columns:
- id
Survey identifier. For file-based documentation, the filename without its extension.
- filename
Original survey filename.
- ncol
Number of variables.
- nrow
Number of observations.
- object_size
Size of the survey object in memory, in bytes.
When documenting source files, three additional columns are returned:
- file_size
Size of the source file in bytes.
- accessed
Last file access time as a character string.
- last_modified
Last file modification time as a character string.
When documenting an in-memory survey list, the result also has an 'original_list' attribute containing the expression supplied as 'survey_list'.
See Also
[metadata_create()], [read_surveys()], [utils::object.size()]
Other documentation functions:
document_survey_item()
Examples
examples_dir <- system.file(
"examples",
package = "retroharmonize"
)
survey_files <- list.files(
examples_dir,
pattern = "\\.rds$",
full.names = TRUE
)
example_surveys <- read_surveys(survey_files)
documented <- document_surveys(
survey_list = example_surveys
)
attr(documented, "original_list")
documented
document_surveys(survey_paths = survey_files)
Harmonize na_values in haven_labelled_spss
Description
Harmonize na_values in haven_labelled_spss
Usage
harmonize_na_values(df)
Arguments
df |
A data frame that contains haven_labelled_spss vectors. |
Value
A tibble where the na_values are consistent
See Also
Other harmonization functions:
collect_val_labels(),
create_codebook(),
crosswalk_surveys(),
harmonize_survey_values(),
harmonize_values(),
harmonize_var_names(),
is.crosswalk_table(),
label_normalize()
Examples
examples_dir <- system.file(
"examples",
package = "retroharmonize"
)
test_read <- read_rds(
file.path(examples_dir, "ZA7576.rds"),
id = "ZA7576",
doi = "test_doi"
)
harmonize_na_values(test_read)
Harmonize values in surveys
Description
Harmonize value codes and value labels across multiple surveys and combine them into a single data frame.
Usage
harmonize_survey_values(survey_list, .f, status_message = FALSE)
harmonize_waves(waves, .f, status_message = FALSE)
Arguments
survey_list |
A list of surveys (data frames). In earlier versions this argument was called
|
.f |
A function applied to each labelled variable
(class |
status_message |
Logical. If |
waves |
A list of surveys. Deprecated. |
Details
The function first aligns the structure of all surveys by ensuring that they contain the same set of variables. Missing variables are added and filled with appropriate missing values depending on their type.
Variables of class "retroharmonize_labelled_spss_survey" are then
harmonized by applying a user-supplied function .f to each variable
separately within each survey.
The harmonization function .f must return a vector of the same length
as its input. If .f returns NULL, the original variable is kept
unchanged.
Prior to version 0.2.0 this function was called harmonize_waves.
The earlier form harmonize_waves is deprecated.
The function is currently called harmonize_waves.
Value
A data frame containing the row-wise combination of all surveys, with harmonized labelled variables and preserved attributes describing the original surveys.
See Also
Other harmonization functions:
collect_val_labels(),
create_codebook(),
crosswalk_surveys(),
harmonize_na_values(),
harmonize_values(),
harmonize_var_names(),
is.crosswalk_table(),
label_normalize()
Examples
examples_dir <- system.file("examples", package = "retroharmonize")
survey_files <- dir(examples_dir, pattern = "\\.rds$", full.names = TRUE)
surveys <- read_surveys(
survey_files,
export_path = NULL
)
# Keep only supported variable types
surveys <- lapply(
surveys,
function(s) {
s[, vapply(
s,
function(x) {
inherits(x, c(
"retroharmonize_labelled_spss_survey",
"numeric",
"character",
"Date"
))
},
logical(1)
)]
}
)
# Identity harmonization (no-op)
harmonized <- harmonize_survey_values(
survey_list = surveys,
.f = function(x) x,
status_message = FALSE
)
head(harmonized)
Read a survey from a CSV file
Description
Import a survey stored in a CSV file and return it as a survey object with attached dataset- and survey-level metadata.
Usage
harmonize_survey_variables(
crosswalk_table,
subset_name = "subset",
survey_list = NULL,
survey_paths = NULL,
import_path = NULL,
export_path = NULL
)
Arguments
crosswalk_table |
A crosswalk table created with [crosswalk_table_create()]. |
subset_name |
Character string appended to filenames of subsetted surveys. Defaults to '"subset"'. |
survey_list |
A list containing surveys of class survey. |
survey_paths |
Optional character vector of file paths to surveys. |
import_path |
Optional base directory used to resolve 'survey_paths'. |
export_path |
Optional directory where subsetted surveys are exported to |
Details
The CSV file is read using [utils::read.csv()]. Character variables with more than one unique value are automatically converted to labelled factors. A unique row identifier is added and labelled.
If the file cannot be read, an empty survey object is returned with a warning.
If a column named '"X"' is present (commonly created by 'write.csv()'), it is removed automatically.
Value
An object of class '"survey"', which is a data frame with attached survey- and dataset-level metadata.
See Also
[read_rds()] for importing surveys from RDS files, [survey_df()] for constructing survey objects manually.
Other import functions:
pull_survey(),
read_csv(),
read_dta(),
read_rds(),
read_spss(),
read_surveys()
Examples
# Create a temporary CSV file from an example survey
path <- system.file("examples", "ZA7576.rds",
package = "retroharmonize"
)
survey <- read_rds(path)
tmp <- tempfile(fileext = ".csv")
write.csv(survey, tmp, row.names = FALSE)
# Read the CSV file back as a survey
re_read <- read_csv(
file = tmp,
id = "ZA7576",
doi = "10.0000/example"
)
Harmonize values and labels of labelled vectors
Description
Convert heterogeneous labelled survey vectors into a harmonized representation with standardized value labels, numeric codes, and missing value definitions.
Usage
harmonize_values(
x,
harmonize_label = NULL,
harmonize_labels = NULL,
na_values = c(do_not_know = 99997, declined = 99998, inap = 99999),
na_range = NULL,
id = "survey_id",
name_orig = NULL,
remove = NULL,
perl = FALSE
)
Arguments
x |
A labelled survey vector. |
harmonize_label |
Optional harmonized variable label. Defaults to the original variable label. |
harmonize_labels |
A list or data frame containing
|
na_values |
Named numeric vector defining harmonized user-defined missing values. |
na_range |
Reserved for compatibility with the original interface. The source vector's missing-value range is retained. |
id |
Survey identifier. If |
name_orig |
Reserved for compatibility with the original
interface. The original object name is derived from |
remove |
Optional regular expression identifying characters to remove before matching. |
perl |
Logical. Use Perl-compatible regular expressions during preliminary label matching. |
Details
The harmonization rules supplied through harmonize_labels
must contain three elements:
-
from: regular expressions matching original value labels. -
to: harmonized value labels. -
numeric_values: harmonized numeric codes.
Matching is case-insensitive. Periods and parentheses are removed before matching.
For exact value-label mappings defined in a crosswalk table,
use crosswalk_surveys().
Value
A retroharmonize_labelled_spss_survey vector containing
harmonized values, labels, missing value definitions, and
source-specific coding metadata.
See Also
crosswalk_surveys(), harmonize_var_names()
Other harmonization functions:
collect_val_labels(),
create_codebook(),
crosswalk_surveys(),
harmonize_na_values(),
harmonize_survey_values(),
harmonize_var_names(),
is.crosswalk_table(),
label_normalize()
Examples
var1 <- labelled::labelled_spss(
x = c(1, 0, 1, 8, 9),
labels = c(
"TRUST" = 1,
"NOT TRUST" = 0,
"DON'T KNOW" = 8,
"INAP. HERE" = 9
),
na_values = c(8, 9)
)
harmonize_values(
var1,
harmonize_labels = list(
from = c("^trust", "^not", "^don", "^inap"),
to = c("trust", "not_trust", "do_not_know", "inap"),
numeric_values = c(1, 0, 99997, 99999)
),
na_values = c("do_not_know" = 99997, "inap" = 99999)
)
Harmonize variable names across surveys
Description
Rename and optionally subset variables across survey datasets using a metadata crosswalk table.
Usage
harmonize_var_names(
survey_list,
metadata,
old = "var_name_orig",
new = "var_name_suggested",
rowids = TRUE
)
Arguments
survey_list |
A list of objects of class [survey()] or [survey_df()], typically imported with [read_surveys()]. |
metadata |
A data frame containing harmonization rules, typically derived from [metadata_create()]. |
old |
Name of the metadata column containing the original variable names. |
new |
Name of the metadata column containing the harmonized variable names. |
rowids |
Reserved for backward compatibility. Row identifier variables are renamed only when explicitly specified in the metadata table. |
Details
Harmonization rules are matched to surveys by filename. Only variables included in the metadata table are retained. The original variable order, observation values, variable attributes and survey-level metadata are preserved.
Identical repeated mappings are accepted. Contradictory mappings, duplicate target names and missing or empty target names are rejected.
If metadata are unavailable for a survey, a warning is issued and a survey with no variables is returned.
Value
A list of surveys with harmonized variable names.
See Also
[metadata_create()], [crosswalk()]
Other harmonization functions:
collect_val_labels(),
create_codebook(),
crosswalk_surveys(),
harmonize_na_values(),
harmonize_survey_values(),
harmonize_values(),
is.crosswalk_table(),
label_normalize()
Examples
examples_dir <- system.file(
"examples",
package = "retroharmonize"
)
survey_files <- list.files(
examples_dir,
pattern = "\\.rds$",
full.names = TRUE
)
example_surveys <- read_surveys(survey_files)
metadata <- metadata_create(example_surveys)
metadata$var_name_suggested <- metadata$var_name_orig
metadata$var_name_suggested[
metadata$var_name_orig == "rowid"
] <- "uniqid"
harmonized_surveys <- harmonize_var_names(
survey_list = example_surveys,
metadata = metadata
)
harmonized_surveys[[1]]
Here
Description
A utility to make sure the system files of the package and other files are always found, regardless if they are in an example or vignette context.
Details
See here::here for details.
Examples
dir(here("inst", "examples"))
Create a crosswalk table
Description
Create a crosswalk table from survey metadata containing source variable names, value codes, labels and variable classes.
Usage
is.crosswalk_table(ctable)
crosswalk_table_create(metadata)
Arguments
ctable |
A data frame to validate as a crosswalk table. |
metadata |
A metadata table created by [metadata_create()]. |
Details
The target columns are initialized from the corresponding source columns or assigned default values. They can be modified manually in a spreadsheet or programmatically to specify harmonization instructions.
Character-coded value labels are not currently supported.
Value
'crosswalk_table_create()' returns a tibble containing source metadata and target columns for harmonization.
'is.crosswalk_table()' returns 'TRUE' if the table is valid and raises an error otherwise.
See Also
Other harmonization functions:
collect_val_labels(),
create_codebook(),
crosswalk_surveys(),
harmonize_na_values(),
harmonize_survey_values(),
harmonize_values(),
harmonize_var_names(),
label_normalize()
Test whether missing values need harmonization
Description
Checks whether both 'na_values' and 'na_range' attributes are present on a labelled vector.
Usage
is.na_range_to_values(x)
Arguments
x |
A labelled vector. |
Value
Logical scalar.
Create a survey object
Description
Construct a survey object from a data frame or tibble by attaching survey-level metadata such as an identifier, source filename, and basic dataset-level descriptive metadata.
Usage
is.survey_df(x)
survey_df(
x,
title = NULL,
creator = person("Unknown", "Creator"),
dataset_bibentry = NULL,
dataset_subject = NULL,
identifier,
filename
)
is.survey_df(x)
## S3 method for class 'survey_df'
print(x, ...)
Arguments
x |
A data frame or tibble containing the survey data. |
title |
Optional title for the survey. Defaults to '"Untitled Survey"'. |
creator |
A [utils::person()] object describing the dataset creator. Defaults to 'person("Unknown", "Creator")'. |
dataset_bibentry |
Optional dataset-level bibliographic metadata. If 'NULL', a minimal DataCite entry is created automatically using 'title', 'creator', and 'dataset_subject'. |
dataset_subject |
Dataset subject metadata. If 'NULL', defaults to the Library of Congress Subject Heading Surveys. |
identifier |
A character scalar identifying the survey. |
filename |
A character scalar giving the source filename, or 'NULL' if unknown. |
... |
potentially further arguments for methods. |
Details
This function is primarily intended for use by import helpers such as [read_rds()], [read_spss()], [read_dta()], and [read_csv()]. Most users will not need to call it directly.
Value
An object of class '"survey_df"', which is a data frame with additional survey-level metadata stored as attributes and dataset-level metadata stored using the 'dataset' package.
See Also
[read_survey()] for importing survey data from external files.
Other importing functions:
survey()
Examples
survey_df(
x = data.frame(
rowid = 1:6,
observations = runif(6)
),
identifier = "example",
filename = "no_file"
)
Normalize value and variable labels
Description
label_normalize removes special characters, whitespace,
and other typical typing errors.
Usage
label_normalize(x)
var_label_normalize(x)
val_label_normalize(x)
Arguments
x |
A character vector of labels to be normalized. |
Details
var_label_normalize and val_label_normalize removes possible
chunks from question identifiers.
The functions var_label_normalize and
val_label_normalize may
be differently implemented for various survey series.
Value
Returns a suggested, normalized label without special characters. The
var_label_normalize and val_label_normalize returns them in
snake_case for programmatic use.
See Also
Other variable label harmonization functions:
na_range_to_values()
Other harmonization functions:
collect_val_labels(),
create_codebook(),
crosswalk_surveys(),
harmonize_na_values(),
harmonize_survey_values(),
harmonize_values(),
harmonize_var_names(),
is.crosswalk_table()
Examples
label_normalize(
c(
"Don't know", " TRUST", "DO NOT TRUST",
"inap in Q.3", "Not 100%", "TRUST < 50%",
"TRUST >=90%", "Verify & Check", "TRUST 99%+"
)
)
var_label_normalize(
c(
"Q1_Do you trust the national government?",
" Do you trust the European Commission"
)
)
val_label_normalize(
c(
"Q1_Do you trust the national government?",
" Do you trust the European Commission"
)
)
Coercion methods for labelled survey vectors
Description
Convert labelled SPSS-style survey vectors to common R data types. These helpers provide consistent coercion behavior for '"retroharmonize_labelled_spss_survey"' objects while respecting labelled missing values.
Usage
as_numeric(x)
as_character(x)
as_factor(x, levels = "default", ordered = FALSE)
Arguments
x |
A labelled survey vector created with [labelled_spss_survey()]. |
levels |
Character string indicating how factor levels should be constructed. Currently retained for compatibility. |
ordered |
Logical; whether the resulting factor should be ordered. Currently ignored. |
Value
* 'as_numeric()' returns a numeric vector with labelled missing values converted to 'NA'. * 'as_character()' returns a character vector based on the factor representation of 'x'. * 'as_factor()' returns a factor with levels derived from value labels.
See Also
[labelled_spss_survey()], [haven::as_factor()]
Other type conversion functions:
as_labelled_spss_survey()
Type and casting methods for labelled survey vectors
Description
Internal vctrs::vctrs-package methods defining how
retroharmonize_labelled_spss_survey vectors interact with
base vectors and with other labelled survey vectors during
concatenation, binding, and coercion.
Usage
## S3 method for class 'retroharmonize_labelled_spss_survey.double'
vec_ptype2(x, y, ...)
## S3 method for class 'double.retroharmonize_labelled_spss_survey'
vec_ptype2(x, y, ...)
## S3 method for class 'integer.retroharmonize_labelled_spss_survey'
vec_ptype2(x, y, ...)
## S3 method for class 'retroharmonize_labelled_spss_survey.integer'
vec_ptype2(x, y, ...)
## S3 method for class 'double.retroharmonize_labelled_spss_survey'
vec_cast(x, to, ...)
## S3 method for class 'integer.retroharmonize_labelled_spss_survey'
vec_cast(x, to, ...)
## S3 method for class 'character.retroharmonize_labelled_spss_survey'
vec_cast(x, to, ...)
Details
Type compatibility between labelled survey vectors requires:
The presence of value labels in both vectors.
Identical sets of labelled value codes.
Identical sets of value labels.
Identical associations between value codes and their labels, irrespective of their ordering.
Compatible user-defined missing values (
na_values).Compatible user-defined missing-value ranges (
na_range).
Incompatible vectors raise a vctrs type error. Differences in value coding or labelling must be resolved through harmonization before the vectors can be combined.
When determining a common type for labelled survey vectors, the methods also retain source-specific historical attributes for subsequent documentation of the harmonisation process.
Combining labelled survey vectors with base numeric vectors produces a base double type. Casting to a base type does not preserve survey-specific metadata.
These methods are part of the internal type system and are not intended to be called directly by users.
See Also
labelled_spss_survey(),
vctrs::vec_ptype2(),
vctrs::vec_cast()
Merge and harmonize surveys
Description
'merge_surveys()' applies a harmonization specification to a list of survey objects and returns harmonized survey datasets with aligned variable names and metadata.
Usage
merge_surveys(survey_list, var_harmonization)
Arguments
survey_list |
A list of survey objects. |
var_harmonization |
A metadata table describing the harmonization rules. The table must contain at least: - 'filename' - 'var_name_orig' - 'var_name_target' - 'var_label' |
Details
Harmonize variable names, labels, and identifiers across multiple surveys using a metadata crosswalk table.
Prior to version 0.2.0 this function was called 'merge_waves()', reflecting terminology commonly used in Eurobarometer surveys.
The harmonization table supplied in 'var_harmonization' typically originates from [metadata_create()] and contains mappings between original and harmonized variable names.
Value
A list of harmonized survey objects with standardized variable names and variable labels.
See Also
[metadata_create()]
Other survey harmonization functions:
merge_waves()
Examples
examples_dir <- system.file(
"examples",
package = "retroharmonize"
)
survey_files <- dir(
examples_dir,
pattern = "\\.rds$",
full.names = TRUE
)
example_surveys <- read_surveys(
survey_files
)
metadata <- metadata_create(
survey_list = example_surveys
)
to_harmonize <- metadata %>%
dplyr::filter(
var_name_orig %in% c("rowid", "w1") |
grepl("^trust", var_label_orig)
) %>%
dplyr::mutate(
var_label = var_label_normalize(var_label_orig),
var_name_target = val_label_normalize(var_label),
var_name_target = ifelse(
.data$var_name_orig %in%
c("rowid", "w1", "wex"),
.data$var_name_orig,
.data$var_name_target
)
)
merged_surveys <- merge_surveys(
survey_list = example_surveys,
var_harmonization = to_harmonize
)
merged_surveys[[1]]
Deprecated wrapper for 'merge_surveys()'
Description
'merge_waves()' has been renamed to [merge_surveys()] for more general survey harmonization workflows.
Usage
merge_waves(waves, var_harmonization)
Arguments
waves |
Deprecated alias for 'survey_list'. |
var_harmonization |
A metadata table describing the harmonization rules. The table must contain at least: - 'filename' - 'var_name_orig' - 'var_name_target' - 'var_label' |
Value
A list of harmonized survey objects.
See Also
[merge_surveys()]
Other survey harmonization functions:
merge_surveys()
Create metadata tables from survey datasets
Description
Extract variable-level metadata from one or more survey datasets supplied as survey objects or survey files.
Usage
metadata_create(survey_list = NULL, survey_paths = NULL, .f = NULL)
metadata_waves_create(survey_list)
Arguments
survey_list |
A survey object or a list of objects of class [survey()] or [survey_df()]. |
survey_paths |
Optional character vector containing paths to survey files. |
.f |
Import function used to read survey files. When NULL, the import function is inferred from the file extension. |
Details
Metadata include variable names, normalized variable labels, imported classes, value labels, user-defined missing values and missing value ranges.
When both 'survey_list' and 'survey_paths' are supplied, 'survey_list' takes precedence.
'metadata_waves_create()' is deprecated. Use 'metadata_create()' instead.
Value
A data frame containing variable-level metadata. Value labels and missing value definitions are stored in list columns.
See Also
[metadata_survey_create()], [create_variable_catalog()]
Other metadata functions:
create_codebook(),
metadata_survey_create()
Examples
examples_dir <- system.file(
"examples",
package = "retroharmonize"
)
survey_paths <- list.files(
examples_dir,
pattern = "\\.rds$",
full.names = TRUE
)
metadata_create(survey_paths = survey_paths)
Create variable-level metadata from a survey dataset
Description
Extract variable-level metadata from a survey dataset. Preserve the original value code-label associations and distinguish valid labels from user-defined missing labels.
Usage
metadata_survey_create(survey)
Arguments
survey |
An object of class [survey()] or [survey_df()]. |
Details
Variable labels are normalized with 'var_label_normalize()'.
Value labels are classified as missing when their codes occur among the user-defined missing values or within the inclusive user-defined missing value range.
Missing metadata are represented by NA values. Value label and missing range columns are always list columns, including for surveys without labelled variables.
For backward compatibility, lists of surveys and character vectors of survey paths are delegated to [metadata_create()].
Value
A nested data frame containing:
- filename
Original survey file name.
- id
Survey identifier.
- var_name_orig
Original variable name.
- class_orig
First imported variable class.
- var_label_orig
Normalized variable label.
- labels
List column of value labels.
- valid_labels
List column of valid value labels.
- na_labels
List column of missing value labels.
- na_range
List column of missing value ranges.
- n_labels
Number of labelled categories.
- n_valid_labels
Number of valid labelled categories.
- n_na_labels
Number of missing labelled categories.
See Also
[metadata_create()], [create_variable_catalog()]
Other metadata functions:
create_codebook(),
metadata_create()
Examples
metadata_survey_create(
read_rds(
system.file(
"examples",
"ZA7576.rds",
package = "retroharmonize"
)
)
)
Harmonize SPSS-style missing value ranges
Description
Ensure consistency between SPSS-style missing value ranges ('na_range') and explicit missing values ('na_values') for labelled survey vectors.
Usage
na_range_to_values(x)
Arguments
x |
A labelled vector created with [haven::labelled_spss()] or 'retroharmonize_labelled_spss_survey'. |
Details
When both attributes are present, this function:
adjusts the missing range if it conflicts with existing missing values,
derives missing values from the range when necessary,
leaves non-SPSS-labelled vectors unchanged.
This harmonization is important before joining, binding, or summarizing survey data.
Value
The input vector with harmonized 'na_values' and 'na_range' attributes. If no harmonization is needed, 'x' is returned unchanged.
See Also
[labelled::na_range()], [labelled::na_values()], [as_numeric()]
Other variable label harmonization functions:
label_normalize()
Labelled SPSS-style vectors with survey provenance
Description
Create a labelled vector compatible with [haven::labelled_spss()] that carries additional survey-level provenance metadata.
Usage
## S3 method for class 'retroharmonize_labelled_spss_survey'
print(x, ...)
labelled_spss_survey(
x = double(),
labels = NULL,
na_values = NULL,
na_range = NULL,
label = NULL,
id = NULL,
name_orig = NULL
)
## S3 method for class 'retroharmonize_labelled_spss_survey'
x[i, ...]
## S3 method for class 'retroharmonize_labelled_spss_survey'
summary(object, ...)
## S3 replacement method for class 'retroharmonize_labelled_spss_survey'
names(x) <- value
## S3 method for class 'retroharmonize_labelled_spss_survey'
is.na(x)
## S3 method for class 'retroharmonize_labelled_spss_survey'
levels(x)
## S3 method for class 'retroharmonize_labelled_spss_survey'
format(x, ..., digits = getOption("digits"))
is.labelled_spss_survey(x)
## S3 method for class 'retroharmonize_labelled_spss_survey'
median(x, na.rm = TRUE, ...)
## S3 method for class 'retroharmonize_labelled_spss_survey'
quantile(x, probs, ...)
## S3 method for class 'retroharmonize_labelled_spss_survey'
weighted.mean(x, w, ...)
## S3 method for class 'retroharmonize_labelled_spss_survey'
mean(x, ...)
## S3 method for class 'retroharmonize_labelled_spss_survey'
sum(x, ...)
Arguments
x |
A vector of values. |
... |
potentially further arguments for methods; not used in the default method. |
labels |
A named vector of value labels. |
na_values |
A vector of values to be treated as missing. |
na_range |
A numeric range defining missing values. |
label |
A variable label. |
id |
A character scalar identifying the survey. |
name_orig |
Original variable name. Defaults to the name of 'x'. |
i |
Index vector used for subsetting. |
object |
A labelled_spss_survey to summarize. |
value |
Replacement values used when assigning names. |
digits |
Number of digits to use in string representation in the format method. |
na.rm |
a logical value indicating whether |
probs |
numeric vector of probabilities with values in
|
w |
a numerical vector of weights the same length as |
Details
The resulting object behaves like a 'haven_labelled_spss' vector, but stores:
a survey identifier;
the original variable name;
the original value coding.
Several arithmetic and statistical summary methods operate on the numeric representation of labelled survey vectors, converting SPSS-style missing values to 'NA' before computation.
You can coerce 'labelled_spss_survey' vectors to numeric, character or factor representation.
Value
An object of class '"retroharmonize_labelled_spss_survey"', extending [haven::labelled_spss()].
See Also
[haven::labelled_spss()], [as_factor()], [as_numeric()], [as_character()]
Examples
x <- labelled_spss_survey(
x = c(1, 2, 9),
labels = c(Yes = 1, No = 2),
na_values = 9,
id = "survey_1"
)
is.na(x)
as_factor(x)
Retrieve a survey from a survey list
Description
'pull_survey()' retrieves a survey object from a list created with [read_surveys()].
Surveys can be selected using:
- the survey identifier stored in the '"id"' attribute, or - the original source file name stored in the '"filename"' attribute.
Usage
pull_survey(survey_list, id = NULL, filename = NULL)
Arguments
survey_list |
A list of 'survey' objects. |
id |
Optional survey identifier. |
filename |
Optional source file name. |
Details
Extract a single 'survey' object from a list of surveys using either its survey identifier or source file name.
Either 'id' or 'filename' must be supplied.
The function throws an error if:
- neither argument is provided; - the requested survey cannot be found; - or multiple surveys match the query.
Value
A single 'survey' object.
See Also
[read_surveys()]
Other import functions:
harmonize_survey_variables(),
read_csv(),
read_dta(),
read_rds(),
read_spss(),
read_surveys()
Examples
examples_dir <- system.file(
"examples",
package = "retroharmonize"
)
survey_files <- dir(
examples_dir,
pattern = "\\.rds$"
)
example_surveys <- read_surveys(
file.path(examples_dir, survey_files)
)
pull_survey(
example_surveys,
id = "ZA5913"
)
Data Input
Description
See utils::read.csv for details.
Read a survey dataset from a CSV file
Description
Import survey data from a comma-separated values (CSV) file into a survey data frame with reproducibility metadata.
Usage
read_csv(file, id = NULL, doi = NULL, dataset_bibentry = NULL, ...)
Arguments
file |
Path to a CSV file. |
id |
Optional survey identifier. If omitted, the file path without its extension is used. |
doi |
Optional digital object identifier (DOI). If omitted, the first value of the 'doi' column is used, when available. |
dataset_bibentry |
Optional bibliographic metadata created with [dataset::dublincore()] or [dataset::datacite()]. |
... |
Reserved for additional import arguments. Currently unused. |
Details
The CSV file must contain a 'rowid' column identifying the observations. Character variables may be converted into defined categorical variables.
If the file cannot be parsed, a warning is issued and an empty survey object is returned.
Value
A 'survey_df' object with survey identifiers, bibliographic metadata, source filename, object size, and source file size. An empty 'survey' object is returned if the file cannot be parsed.
See Also
Other import functions:
harmonize_survey_variables(),
pull_survey(),
read_dta(),
read_rds(),
read_spss(),
read_surveys()
Examples
path <- system.file(
"examples",
"ZA7576.rds",
package = "retroharmonize"
)
example_survey <- read_rds(path)
csv_file <- tempfile(fileext = ".csv")
utils::write.csv(
x = example_survey,
file = csv_file,
row.names = FALSE
)
imported_survey <- read_csv(
file = csv_file,
id = "ZA7576"
)
unlink(csv_file)
Read a Stata survey file
Description
Import a Stata ('.dta') survey file with harmonized variable labels, value labels and survey metadata.
Usage
read_dta(file, id = NULL, doi = NULL, .name_repair = "unique")
Arguments
file |
Path to a Stata survey file. |
id |
Optional survey identifier. Defaults to the filename without its extension. |
doi |
Optional DOI identifier for the survey. |
.name_repair |
Column name repair strategy passed to [haven::read_dta()]. |
Details
This function wraps [haven::read_dta()] and adds survey-specific observation identifiers, harmonized labelled vectors and provenance metadata.
Variables with value labels are converted to 'labelled_spss_survey' vectors. Labelled numeric or character variables without value label definitions are converted to ordinary vectors.
Variable labels and the original column order are preserved. A 'rowid' column is added as the first variable, with observation identifiers prefixed by the survey identifier.
If an existing file cannot be imported by haven, an empty survey is returned with a warning. Nonexistent files raise an error.
Value
A [survey()] object inheriting from 'data.frame' and 'tbl_df', with survey metadata and provenance attributes.
Additional attributes include:
- 'object_size': size of the imported data in bytes. - 'source_file_size': size of the source file in bytes.
See Also
[read_surveys()], [read_spss()], [read_rds()]
Other import functions:
harmonize_survey_variables(),
pull_survey(),
read_csv(),
read_rds(),
read_spss(),
read_surveys()
Examples
path <- system.file(
"examples",
"iris.dta",
package = "haven"
)
survey_object <- read_dta(path)
attr(survey_object, "id")
attr(survey_object, "filename")
Read a survey from an '.rds' file
Description
Import a serialized survey object stored in '.rds' format and return it as a 'survey' object with harmonized metadata attributes.
Usage
read_rds(file, dataset_bibentry = NULL, id = NULL, doi = NULL)
Arguments
file |
Path to an '.rds' file containing a survey object. |
dataset_bibentry |
Optional bibliographic metadata created with [dataset::dublincore()] or [dataset::datacite()]. |
id |
Optional survey identifier. Defaults to the file name without extension. |
doi |
Optional DOI identifier for the survey. |
Details
This function restores survey objects previously saved with [base::saveRDS()] or exported from the 'retroharmonize' workflow. The returned object retains survey metadata and gains additional provenance attributes such as source file name and file size.
If the file cannot be read, an empty 'survey' object is returned and a warning is emitted.
The function:
- restores the serialized object, - validates source file information, - normalizes 'rowid', - records provenance metadata, - and stores object and source file sizes as attributes.
Value
A 'survey' object inheriting from 'data.frame' and 'tbl_df' with survey metadata attributes.
See Also
Other import functions:
harmonize_survey_variables(),
pull_survey(),
read_csv(),
read_dta(),
read_spss(),
read_surveys()
Examples
path <- system.file(
"examples",
"ZA7576.rds",
package = "retroharmonize"
)
survey_object <- read_rds(path)
attr(survey_object, "id")
attr(survey_object, "filename")
attr(survey_object, "doi")
Read an SPSS survey file
Description
Import an SPSS survey file in '.sav', '.zsav' or '.por' format with harmonized variable labels, value labels, missing value definitions and survey metadata.
Usage
read_spss(
file,
user_na = TRUE,
dataset_bibentry = NULL,
id = NULL,
doi = NULL,
.name_repair = "unique"
)
Arguments
file |
Path to an SPSS survey file. |
user_na |
Logical. Preserve user-defined missing values and their definitions? Defaults to 'TRUE'. |
dataset_bibentry |
Optional bibliographic metadata created with [dataset::dublincore()] or [dataset::datacite()]. |
id |
Optional survey identifier. Defaults to the filename without its extension. |
doi |
Optional DOI identifier for the survey. |
.name_repair |
Column name repair strategy passed to [haven::read_spss()]. |
Details
This function wraps [haven::read_spss()] and adds survey-specific observation identifiers, harmonized labelled vectors and provenance metadata.
Variables with value labels or user-defined missing value definitions are converted to 'labelled_spss_survey' vectors.
User-defined missing codes and missing ranges are preserved when 'user_na = TRUE', even when the source variable has no value labels.
When 'user_na = FALSE', user-defined missing values are converted to ordinary 'NA' values by haven.
Labelled numeric or character variables without value labels or missing value definitions are converted to ordinary vectors.
Variable labels and original column order are preserved. A 'rowid' column is added as the first variable, with observation identifiers prefixed by the survey identifier.
If an existing file cannot be imported by haven, an empty survey is returned with a warning. Nonexistent files raise an error.
Value
A [survey_df()] object with survey metadata, labelled variables and provenance attributes.
Additional attributes include:
- 'id': survey identifier. - 'doi': DOI identifier, when available. - 'filename': original source filename. - 'object_size': size of the imported data in bytes. - 'source_file_size': size of the source file in bytes.
An unreadable file returns an empty [survey()] object.
See Also
[read_surveys()], [read_dta()], [read_rds()], [labelled_spss_survey()]
Other import functions:
harmonize_survey_variables(),
pull_survey(),
read_csv(),
read_dta(),
read_rds(),
read_surveys()
Examples
path <- system.file(
"examples",
"iris1.sav",
package = "retroharmonize"
)
survey_object <- read_spss(path)
attr(survey_object, "id")
attr(survey_object, "filename")
Read survey files into memory or save as RDS files
Description
Import one or more survey files using a consistent survey import interface.
Usage
read_surveys(
survey_paths,
.f = NULL,
export_path = NULL,
ids = NULL,
dois = NULL,
...
)
Arguments
survey_paths |
A character vector of paths to survey files. |
.f |
An import function, a supported import function name, or 'NULL' for automatic format detection. |
export_path |
Optional directory where imported surveys are saved as RDS files. |
ids |
Optional character vector of survey identifiers, with one element per supplied file. |
dois |
Optional character vector of DOI identifiers, with one element per supplied file. |
... |
Additional arguments passed to the import function. |
Details
When '.f' is 'NULL', the import function is selected automatically from the file extension, regardless of case.
The supported formats and corresponding import functions are:
- '.sav', '.por'
[read_spss()]
- '.dta'
[read_dta()]
- '.rds'
[read_rds()]
- '.csv'
[read_csv()]
Alternatively, supply a supported import function name or a function object through '.f'.
Custom import functions must accept a file path as their first argument and return a survey object. Additional arguments are forwarded to the import function.
Missing files are excluded with a warning. If none of the supplied files exist, an error is raised.
Errors raised during import are reported and a 'NULL' element is returned for the affected file.
When 'export_path' is supplied, imported surveys are saved using [base::saveRDS()]. If the export directory does not exist, the survey is returned in memory with a warning.
Value
A list containing one element per existing input file.
When 'export_path' is 'NULL', the elements are [survey()] or [survey_df()] objects.
When export succeeds, the corresponding list elements contain the exported RDS filenames.
Import errors may result in 'NULL' elements.
See Also
[survey()], [survey_df()], [read_rds()], [read_spss()], [read_dta()], [read_csv()]
Other import functions:
harmonize_survey_variables(),
pull_survey(),
read_csv(),
read_dta(),
read_rds(),
read_spss()
Examples
examples_dir <- system.file(
"examples",
package = "retroharmonize"
)
survey_files <- list.files(
examples_dir,
pattern = "\\.rds$",
full.names = TRUE
)
surveys <- read_surveys(survey_files)
surveys <- read_surveys(
survey_files,
.f = "read_rds"
)
surveys <- read_surveys(
survey_files,
.f = read_rds
)
retroharmonize: Retrospective harmonization of survey data files
Description
The goal of retroharmonize is to facilitate retrospective (ex-post)
harmonization of data, particularly survey data, in a reproducible manner.
The package provides tools for organizing the metadata, standardizing the
coding of variables, variable names and value labels, including missing
values, and for documenting all transformations, with the help of
comprehensive S3 classes.
import functions
Read data stored in formats with rich metadata, such as SPSS (.sav) files,
and make them usable in a programmatic context.
read_spss: read an SPSS file and record metadata for reproducibility
read_rds: read an rds file and record metadata for reproducibility
read_surveys: programmatically read a list of surveys
pull_survey: pull a single survey from a survey list.
subsetting functions
subset_surveys: remove variables from surveys that cannot be harmonized.
variable name harmonization functions
harmonize_survey_variables: Create a list of surveys with harmonized variable names.
variable label harmonization functions
Create consistent coding and labelling.
harmonize_values: Harmonize the label list across surveys.
harmonize_survey_values: Create a list of surveys with harmonized value labels.
na_range_to_values: Make the na_range attributes,
as imported from SPSS, consistent with the na_values attributes.
label_normalize removes special characters, whitespace,
and other typical typing errors and helps the uniformization of labels
and variable names.
survey harmonization functions
merge_surveys: Create a list of surveys with harmonized names and variable labels.
crosswalk_surveys: Create a list of surveys with harmonized variable names, harmonized
value labels and harmonize R classes.
crosswalk: Create a joined data frame of surveys with harmonized variable names, harmonized
value labels and harmonize R classes.
metadata functions
metadata_create: Createa metadata dataa from one or more survey.
metadata_survey_create: Create a joined metadata data frame from one survey.
create_codebook and codebook_waves_create
crosswalk_table_create: Create an initial crosswalk table from a metadata data frame.
documentation functions
Make the workflow reproducible by recording the harmonization process.
document_survey_item: Returns a list of the current and historic coding,
labelling of the valid range and missing values or range, the history of the variable names
and the history of the survey IDs.
document_surveys: Document the key attributes surveys in a survey list.
type conversion functions
Consistently treat labels and SPSS-style user-defined missing
values in the R language.
survey helps constructing a valid survey data frame, and
labelled_spss_survey helps creating a vector for a
questionnaire item.
as_numeric: convert to numeric values.
as_factor: convert to labels to factor levels.
as_character: convert to labels to characters.
as_labelled_spss_survey: convert labelled and labelled_spss
vectors to labelled_spss_survey vectors.
Author(s)
Maintainer: Daniel Antal daniel.antal@dataobservatory.eu (ORCID)
Authors:
Daniel Antal daniel.antal@dataobservatory.eu (ORCID)
Other contributors:
Marta Kolczynska mkolczynska@gmail.com (ORCID) [contributor]
See Also
Useful links:
Report bugs at https://github.com/dataobservatory-eu/retroharmonize/issues
Subset surveys
Description
Retain selected variables from one or more surveys, either loaded in memory or read sequentially from files.
Usage
subset_surveys(
survey_list = NULL,
survey_paths = NULL,
rowid = "rowid",
subset_name = "subset",
subset_vars = NULL,
crosswalk_table = NULL,
import_path = NULL,
export_path = NULL
)
Arguments
survey_list |
A survey object or a list of survey objects. If 'NULL', surveys are read from files. |
survey_paths |
A character vector of survey file paths. |
rowid |
Name of the observation identifier column. Defaults to '"rowid"'. |
subset_name |
Character string appended to subset filenames. |
subset_vars |
Character vector of variables to retain. If 'NULL', all variables are retained unless a crosswalk table is supplied. |
crosswalk_table |
An optional crosswalk table created with [crosswalk_table_create()]. |
import_path |
Optional directory containing survey files. |
export_path |
Optional directory for exporting subsetted surveys as RDS files. |
Details
When a crosswalk table is supplied, surveys are matched by their identifiers and variables are selected using 'var_name_orig'. Original variable names, values and labels are preserved.
In-memory surveys retain their original ordering. Crosswalk rows do not determine survey ordering.
Variables unavailable in a survey are silently omitted.
Value
A list of subsetted survey objects, or a character vector of exported filenames when 'export_path' is supplied.
See Also
[crosswalk_table_create()], [crosswalk()], [read_surveys()]
Examples
s <- read_rds(
system.file("examples", "ZA7576.rds",
package = "retroharmonize"
)
)
subset_surveys(
survey_list = s,
subset_vars = c("rowid", "isocntry", "qa14_1"),
subset_name = "example"
)
Create a survey data frame
Description
Store survey data in a tibble with a unique survey identifier, source filename, and optional digital object identifier (DOI).
Usage
survey(object = data.frame(), id = "survey_id", filename = NULL, doi = NULL)
is.survey(object)
## S3 method for class 'survey'
summary(object, ...)
Arguments
object |
A data frame or tibble containing the survey data. |
id |
A unique identifier for the survey. |
filename |
The name of the source file. |
doi |
An optional digital object identifier (DOI). |
... |
Arguments passed to summary method. |
Details
Survey objects can be created directly with this constructor. More commonly, they are created by the import functions [read_rds()], [read_spss()], [read_dta()], and [read_csv()], or through the common import interface [read_surveys()].
Value
A tibble of class 'survey' with survey-level metadata stored in the 'id', 'filename', and 'doi' attributes.
See Also
Other importing functions:
is.survey_df()
Examples
example_survey <- survey(
object = data.frame(
rowid = 1:6,
observations = runif(6)
),
id = "example",
filename = "no_file"
)
Convert labelled missing values to NA
Description
Internal helper used by numeric summary methods to replace SPSS-style missing values with 'NA'.
Usage
vec_convert_na(x)
Arguments
x |
A labelled survey vector. |
Value
A numeric vector with missing values converted to 'NA'.