savedata: Save data according to file extension

View source: R/data-management.R

savedataR Documentation

Save data according to file extension

Description

Saves active data or an explicitly supplied data frame. Variables and observations can be selected without changing the source data.

Usage

savedata(
  data = NULL,
  file = NULL,
  vars = NULL,
  obs = NULL,
  sheet = "Data",
  header = TRUE,
  sep = NULL,
  na = "",
  encoding = "UTF-8",
  replace = FALSE,
  quiet = FALSE,
  ...
)

Arguments

data

Data frame, or output path when saving active data.

file

Output path. Omit when the first argument is the path.

vars

Optional variables to save.

obs

Optional observations to save. missing(x) is supported.

sheet

Excel sheet name.

header

Logical; write variable names for text files.

sep

Text-file delimiter. Defaults from extension.

na

Missing-value text for delimited files.

encoding

Text encoding.

replace

Logical; overwrite an existing file.

quiet

Logical; suppress summary messages.

...

Additional writer arguments.

Details

Use savedata("file.csv") for active data, or savedata(data, "file.csv") for an explicit data frame.

Value

The normalized saved path invisibly.

Examples

d <- datasets::iris
usedf(d, quiet = TRUE)

# Base-R formats: short examples run during R CMD check.
f_csv <- tempfile(fileext = ".csv")
f_sub <- tempfile(fileext = ".csv")
f_rds <- tempfile(fileext = ".rds")

savedata(f_csv, quiet = TRUE)
savedata(
  f_sub,
  vars = vars(Sepal.Length, Species),
  obs = Species == "setosa",
  quiet = TRUE
)
savedata(d, f_rds, quiet = TRUE)
unlink(c(f_csv, f_sub, f_rds))
usedf(clear = TRUE, quiet = TRUE)

# Optional formats are guarded because their writers are in Suggests.
if (requireNamespace("writexl", quietly = TRUE) ||
    requireNamespace("openxlsx", quietly = TRUE)) {
  f <- tempfile(fileext = ".xlsx")
  savedata(d, f, sheet = "Data", quiet = TRUE)
  unlink(f)
}

if (requireNamespace("haven", quietly = TRUE)) {
  # Stata/SPSS impose variable-name rules. Use portable names here.
  d_haven <- data.frame(
    sepal_length = d$Sepal.Length,
    sepal_width = d$Sepal.Width,
    petal_length = d$Petal.Length,
    petal_width = d$Petal.Width,
    species = as.character(d$Species),
    stringsAsFactors = FALSE
  )
  f_dta <- tempfile(fileext = ".dta")
  f_sav <- tempfile(fileext = ".sav")
  savedata(d_haven, f_dta, quiet = TRUE)
  savedata(d_haven, f_sav, quiet = TRUE)
  unlink(c(f_dta, f_sav))
}

if (requireNamespace("jsonlite", quietly = TRUE)) {
  f <- tempfile(fileext = ".json")
  savedata(d, f, quiet = TRUE)
  unlink(f)
}


if (requireNamespace("arrow", quietly = TRUE)) {
  f <- tempfile(fileext = ".parquet")
  savedata(d, f, quiet = TRUE)
  unlink(f)
}


R4VN documentation built on Sept. 30, 2026, 5:13 p.m.