# A small dataset with variable and value labels
survey <- data.frame(
age = declared(
c(28, 35, 42),
label = "Age in years"
),
device = declared(
c(1, 2, 1),
label = "Device used",
labels = c(Desktop = 1, Mobile = 2)
)
)
# Use a temporary directory for the files created in this example
temp_dir <- tempdir()
csv_file <- file.path(temp_dir, "survey.csv")
admisc::export(undeclare(survey, drop = TRUE), file = csv_file)
# codeBook is an R object containing DDI metadata extracted from survey.
# It describes the variables and their labels; the observations are in the CSV.
codeBook <- getCodebook(survey)
# Create Stata commands to import the CSV and apply the metadata
# Edit the generated file's configuration paths before running it in Stata.
setupfile(codeBook, file = file.path(temp_dir, "survey.do"), csv = csv_file)
# A labelled data frame can also be supplied directly
setupfile(survey, file = file.path(temp_dir, "survey.sps"))
# The file extension selects the software: .do, .sps, .sas or .R.
# A setup file contains import commands, not the observations themselves.
if (FALSE) {
# Alternatively, read metadata from an existing DDI XML file
setupfile("/path/to/metadata.xml", file = "survey.do",
csv = "/path/to/survey.csv")
# Batch processing: read metadata and CSV files from matching directories
setupfile("/path/to/metadata/directory", csv = "/path/to/csv/directory")
}
Run the code above in your browser using DataLab