A wrapper around dput
that facilitates saving R objects within knitr documents.
Automatically handles file naming and directory creation, with support for
preserving object structure and attributes.
Usage
write_obj(obj, file = NULL, target_dir = NULL, ...)
Arguments
- obj
The R object to be written.
- file
The name of the file to be written. If not specified, the
label of the code block will be used.
- target_dir
The directory where the file will be written. If not
specified, the current working directory will be used.
- ...
Additional arguments to be passed to dput
.
Value
The path of the written file.
Details
This function extends dput
functionality by:
Using knitr code block labels for automatic file naming
Creating target directories if they don't exist
Preserving complex object structures and attributes
Supporting all R object types (vectors, lists, data frames, etc.)
Objects saved with this function can be read back using the standard
dget
function.
Examples
if (FALSE) { # \dontrun{
obj_dir <- file.path(tempdir(), "obj")
# Write a data frame as a file
write_obj(
obj = mtcars,
file = "mtcars_data",
target_dir = obj_dir
)
# Read the file back into an R session
my_mtcars <- dget(file.path(obj_dir, "mtcars_data"))
unlink(obj_dir)
} # }