write_obj: Write an R object as a file

View source: R/write_obj.R

write_objR Documentation

Write an R object as a file

Description

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.

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.

Value

The path of the written file.

Examples

## Not run: 
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)

## End(Not run)

qtkit documentation built on April 4, 2025, 4:47 a.m.