| Type: | Package |
| Title: | Easily Save Output and Trace it Back to Code |
| Version: | 0.1.0 |
| Maintainer: | Philip Delff <philip@delff.dk> |
| Description: | Write output (plots and tables) ensuring traceability back to code. Includes a graphics saver with simple automation of stamping with source, destination and creation time. A list of plots can be saved at once. A user-friendly selection of output dimensions for presentations, on-screen inspections, and more available. |
| License: | MIT + file LICENSE |
| URL: | https://nmautoverse.github.io/tracee/, https://github.com/NMautoverse/tracee |
| BugReports: | https://github.com/NMautoverse/tracee/issues |
| RoxygenNote: | 7.3.3 |
| Depends: | R (≥ 4.0.0) |
| Imports: | NMdata (≥ 0.2.4), data.table, ggplot2, grid, gridExtra, flextable, patchwork, ragg |
| VignetteBuilder: | knitr |
| Suggests: | testthat, withr, knitr, rmarkdown, magick |
| Encoding: | UTF-8 |
| Config/testthat/edition: | 3 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-24 13:31:52 UTC; delff |
| Author: | Philip Delff [aut, cre] |
| Repository: | CRAN |
| Date/Publication: | 2026-11-24 14:20:01 UTC |
Call a path function safely, forwarding script only if supported
Description
Internal helper used by ggwrite, ftwrite,
datwrite, and lwrite to call a fun.path
function (as returned by pathFormat, or user-supplied) with
name, model, subdir, and (if supported) script.
This avoids "unused argument" errors when a custom fun.path function
does not accept a script argument.
Usage
applyFunPath(
fun.path,
name,
model = NULL,
script = NULL,
subdir = NULL,
quiet = FALSE
)
Arguments
fun.path |
A function as returned by |
name |
Character string, file name passed to |
model |
Model identifier passed to |
script |
Script identifier. Only forwarded to |
subdir |
Subdirectory passed to |
quiet |
Logical. If |
Value
The result of calling fun.path with the applicable arguments.
Resolve path.format (and deprecated fun.path) to a path function
Description
Internal helper used by ggwrite, ftwrite,
datwrite, and writer.
Usage
argPathFormat(path.format = NULL, fun.path = NULL)
Arguments
path.format |
Character string, function or |
fun.path |
Deprecated alias for |
Value
A path function as returned by pathFormat, or
NULL if neither argument is given.
Extract arguments from a traceit object
Description
This function retrieves stored arguments from a traceit object's attributes and returns those that match the formal arguments of a given function, excluding arguments that were already supplied in the current call.
Usage
argsFromTrace(fun, x, attr = "args")
Arguments
fun |
A function whose formal arguments will be matched against the stored arguments in the traceit object |
x |
An object to extract arguments from. Must inherit from "traceit" class, otherwise an empty list is returned |
attr |
Character string specifying the name of the attribute containing the stored arguments. Default is "args" |
Details
This function is used internally to retrieve default arguments that were
previously stored in a traceit object (via traceit() functions) and
apply them to subsequent function calls. It ensures that explicitly provided
arguments take precedence over stored defaults.
Value
A named list of arguments that:
Match formal arguments of
fun(excluding "x")Were stored in the traceit object's attributes
Were NOT already supplied in the current function call
Returns an empty list if x does not inherit from "traceit" or if
the specified attribute is not a list.
Examples
## Not run:
# Assuming a traceit object with stored arguments
p <- traceit(ggplot(mtcars, aes(x = mpg, y = hp)) + geom_point(),
canvas = "wide", formats = "png")
# argsFromTrace would extract canvas and formats if not already specified
args <- argsFromTrace(ggwrite, p)
## End(Not run)
Get predefined canvas sizes
Description
Get predefined canvas sizes
Usage
canvasSize(canvas, scale = 1, simplify = TRUE)
Arguments
canvas |
Can either be a character with one of the values
or it can be a list with elements width and height with single values (unit is inches). Example: canvas=list(height=5,width=9). |
scale |
A scale to apply to both directions of the canvas size. This can be useful in combination with the pre-defined canvas sizes. |
simplify |
If only one canvas returned and simplify=TRUE, the result will not be wrapped in a list. For programming, you most likely want simplify=FALSE to be sure to always get the same format back. |
Value
A list with numerical elements width and height as used by ggwrite.
See Also
Other Plotting:
ggstamp(),
ggwater(),
ggwrite()
Check if list element names are allowed
Description
Internal function to validate that all names in a list are within a set of allowed element names. Throws an error if any disallowed names are found.
Usage
checkNames(x, elems.allowed = NULL, name.x = "x")
Arguments
x |
A named list to check. |
elems.allowed |
Character vector of allowed element names. If NULL, all names are allowed and the function returns x unchanged. |
name.x |
Character string used in error messages to identify the object being checked. Default is "x". |
Details
This function is used internally to validate argument lists before passing them to other functions. It helps catch typos or invalid arguments early.
Value
Returns x unchanged if all names are allowed.
Drop spaces and odd characters. Use to ensure generated file names are usable.
Description
Drop spaces and odd characters. Use to ensure generated file names are usable.
Usage
cleanFileNames(x, allow.slash = FALSE)
Arguments
x |
a string to clean |
Value
A character vector
Create a stamp with script path, output file path and time stamp in it.
Description
Create a stamp with script path, output file path and time stamp in it.
Usage
createStamp(
file,
script,
time,
model,
addto,
stamp.format,
stamp.funs = list(script = function(x) paste("Script:", x), time = function(x)
paste("Time:", if (inherits(x, "POSIXt")) format(x, "%d-%b-%Y %H:%M") else x),
model = function(x) paste("Model:", x), file = function(x) paste("Output:", x))
)
Arguments
file |
the output file path |
script |
The script path |
time |
The default is to insert a time stamp taken from result of Sys.time(). Using the time argument you can overrule this by setting a fixed string instead. Use "" to omit. |
model |
An optional model name or object to be included in the stamp. |
addto |
An existing caption to keep above the caption created by this function. |
stamp.format |
A template for the stamp text using the
placeholders |
stamp.funs |
Named list of functions used to preprocess
|
Value
A character string, or NULL if neither
script nor model is given.
Write data to file(s) using NMwriteData
Description
This function writes data objects to files, with support for lists of data objects. It wraps NMwriteData and provides additional functionality for file path construction and metadata stamping.
Usage
datwrite(
x,
file,
script,
time,
model,
formats,
path.format = NULL,
subdir = NULL,
quiet = FALSE,
fun.path = NULL,
...
)
Arguments
x |
A data frame or list of data frames to write |
file |
Character string specifying the output file name |
script |
Optional character string specifying the script name for stamping |
time |
Optional time stamp to include in output |
model |
Optional model object or path for organizing output files |
formats |
Character vector of output formats (passed to NMwriteData) |
path.format |
Character string or function defining the output path.
Passed to |
subdir |
Optional subdirectory for organizing output files |
quiet |
Logical. If |
fun.path |
Deprecated. Use |
... |
Additional arguments passed to NMwriteData |
Value
A list of results from NMwriteData calls
Write a single data object to file
Description
Internal function that handles writing a single data frame to file using NMwriteData. Constructs file paths, prepares stamping arguments, and calls NMwriteData with appropriate parameters.
Usage
datwriteOne(
x,
file,
formats,
script,
time,
model,
fun.path,
subdir = NULL,
quiet = FALSE,
...
)
Arguments
x |
A data frame to write |
file |
Character string specifying the output file name |
formats |
Character vector of output formats |
script |
Optional character string specifying the script name for stamping |
time |
Optional time stamp to include in output |
model |
Optional model object or path for organizing output files |
fun.path |
Path function as returned by |
subdir |
Optional subdirectory for organizing output files |
quiet |
Logical. If |
... |
Additional arguments passed to NMwriteData |
Value
Result from NMwriteData call
Stamp and write flextab objects to one or multiple formats
Description
Stamp and write flextab objects to one or multiple formats
Usage
ftstamp(
ft,
file,
script,
time,
model,
stamp.ft.style,
stamp.format = NULL,
stamp.funs = NULL
)
Arguments
ft |
a flextable object |
file |
The file that the flextable will be written to (no file is written by this function) |
script |
path to script - will be pasted as caption. |
time |
The default is to insert a time stamp taken from result of Sys.time(). Using the time argument you can overrule this by setting a fixed string instead. Use "" to omit. |
model |
Character string or model object specifying the model name/identifier.
Used for stamping. If a list (model object) is provided, the |
stamp.ft.style |
A list specifying formatting options for the stamp. Valid
elements include: |
stamp.format |
A template for the stamp text using the
placeholders |
stamp.funs |
Optional named list of functions (elements |
Value
A flextable object with the stamp added as a footer line.
Write flextable objects to one or multiple file formats
Description
Writes flextable objects to various file formats with optional stamping
(caption with script name, timestamp, and model information). Can write single
flextables or lists of flextables, with automatic file naming and directory
structure organization.
Usage
ftwrite(
ft,
file,
formats,
save = TRUE,
show = !save,
quiet = FALSE,
script,
time,
model,
stamp.ft.style,
path.format = NULL,
subdir = NULL,
use.names = TRUE,
stamp.format = NULL,
stamp.funs = NULL,
fun.path = NULL
)
writeFlextab(ft, file, script, formats, save, quiet = FALSE, ...)
Arguments
ft |
A |
file |
Character string specifying the base file name to save to (without
extension). The actual extension(s) will be determined by the |
formats |
Character vector specifying one or more output formats. Supported
formats are: "png", "docx", "pptx", "html", "rds". Default is |
save |
Logical. Should the table be saved to file? Default is |
show |
Logical. Should the flextable be printed/displayed? Default is the
opposite of |
quiet |
Logical. If |
script |
Character string or path to the script file. If provided, will be included in the table stamp/caption. This helps document which script generated the output. |
time |
Character string or POSIXct timestamp. The default behavior is to
include a timestamp if |
model |
Character string or model object specifying the model name/identifier.
Used for stamping and for organizing output directories via |
stamp.ft.style |
A list of formatting options for the stamp,
passed to |
path.format |
Character string or function defining the output path.
A template using |
subdir |
Character string specifying a subdirectory within the path structure.
Used in conjunction with |
use.names |
Logical. If |
stamp.format |
A template for the stamp text using the
placeholders |
stamp.funs |
Optional named list of functions (elements |
fun.path |
Deprecated. Use |
... |
Additional arguments passed to |
Details
The function handles both single flextable objects and lists of flextables:
For single flextables: writes to file(s) with name specified by
fileFor lists of flextables: writes each element to a separate file, with names constructed from
fileand the list element names
When ft is a list:
Named list elements use their names in the output file names
Unnamed elements are automatically numbered with zero-padded indices
Multiple formats can be written simultaneously by specifying a vector of formats. Each format will be saved as a separate file with the appropriate extension.
Value
Invisibly returns the result from ftwriteOne (for lists,
returns results for all written tables). If show = TRUE, also prints
the flextable(s) to the current device.
Functions
-
writeFlextab(): Deprecated function name. Use ftwrite.
File Formats
The following formats are supported via the flextable package save functions:
-
"png": Image format viasave_as_image -
"docx": Microsoft Word viasave_as_docx -
"pptx": Microsoft PowerPoint viasave_as_pptx -
"html": HTML format viasave_as_html -
"rds": R data format (saves the flextable object itself)
See Also
ftwriteOne for writing a single flextable,
ftstamp for adding stamps to flextables,
writer for a unified interface to write various object types,
pathFormat for organizing output directories,
save_as_image,
save_as_docx,
save_as_pptx,
save_as_html
Examples
## Not run:
library(flextable)
# Create a simple flextable
ft1 <- flextable(head(mtcars))
# Write to PNG (default format)
ftwrite(ft1, file = "mytable")
# Write to multiple formats
ftwrite(ft1, file = "mytable", formats = c("png", "docx", "html"))
# Write with stamping
ftwrite(ft1, file = "mytable",
script = "analysis.R",
model = "run001")
# Write a list of tables
ft_list <- list(
summary = flextable(summary(mtcars)),
head = flextable(head(mtcars)),
tail = flextable(tail(mtcars))
)
ftwrite(ft_list, file = "tables", formats = "docx")
# Creates: tables_summary.docx, tables_head.docx, tables_tail.docx
# Use with path structure for model organization
ftwrite(ft1, file = "summary",
model = "run001",
path.format = "%model/%name_%model")
# Writes to: run001/summary_run001.png
## End(Not run)
Write a single flextable object to file(s)
Description
Internal function called by ftwrite to handle writing of individual
flextable objects. Generally not called directly by users.
Usage
ftwriteOne(
ft,
file,
formats,
save = TRUE,
show = !save,
quiet = FALSE,
script,
time,
model,
stamp.ft.style,
fun.path,
subdir,
stamp.format = NULL,
stamp.funs = NULL
)
Arguments
ft |
A |
file |
Character string, base file name (without extension). |
formats |
Character vector of output format(s). See |
save |
Logical, whether to save to file. Default |
show |
Logical, whether to display the table. Default |
quiet |
Logical, suppress messages. Default |
script |
Character string, path to script for stamping. |
time |
Character string or POSIXct, timestamp for stamping. |
model |
Character string or model object, model identifier for stamping. |
stamp.ft.style |
Format specification for stamp. Passed to |
fun.path |
Function for constructing file paths. See |
subdir |
Character string, subdirectory for outputs. |
stamp.format, stamp.funs |
Passed to |
Value
If show = TRUE, returns the flextable object (possibly stamped).
Otherwise returns invisibly a list of file paths written.
See Also
Always stamp your plots with script name
Description
This function is used to stamp ggplot type plots with datetime and script name. User must provide the script name.
Usage
ggstamp(
plot,
file,
size,
script,
time,
model,
stamp.gg.style,
stamp.format = NULL,
stamp.funs = NULL
)
Arguments
plot |
The plot to be stamped. |
file |
An optional output filename to be included in the stamp. |
size |
The size (list) for the plot, not the caption. Used to calculate the size of the caption. |
script |
the script name. Date and time will be added automatically. |
time |
The timestamp to be included. |
model |
An optional model name or object to be included in the stamp. |
stamp.gg.style |
A list of formatting options for the stamp text. For ggplot objects,
valid elements include size, colour, hjust, vjust, and other parameters accepted by
|
stamp.format |
A template for the stamp text using the
placeholders |
stamp.funs |
Optional named list of functions (elements |
Details
The stamp text is generated by createStamp
based on stamp.format and stamp.funs. If the
plot already has a caption, the stamp is added below it.
How the stamp is added depends on size:
If
sizeis given (always the case when called fromggwrite), the stamp is drawn in a separate panel underneath the plot (combined usingpatchwork). The panel height is calculated from the number of stamp lines and the font size, and the plot height is reduced accordingly so the total size matchessize. Placement of the stamp (stamp.gg.style$position) and justification of its lines (stamp.gg.style$hjust) are controlled independently.If
sizeis not given, the stamp is added as the plot caption (labs(caption=...)) and styled usingtheme(plot.caption=...). In this case,hjustcontrols both placement and justification.
For gtable objects (e.g. from gridExtra::arrangeGrob), the
stamp is added at the bottom using arrangeGrob.
ggplot 2.2.1 or newer is required.
Value
A stamped plot object. If size is given, a
patchwork object with the stamp panel underneath the plot.
Otherwise the plot with the stamp added as caption. For gtable
input, a gtable. If plot is a list, a list of stamped
plots.
See Also
Other Plotting:
canvasSize(),
ggwater(),
ggwrite()
Examples
library(ggplot2)
data(ChickWeight)
p1 <- ggplot(ChickWeight,aes(Time,weight,group=Chick,colour=factor(Diet)))+geom_line()
script <- "note"
ggstamp(p1,script)
## Or use ggwrite which will call ggstamp when the `script` argument is provided.
ggwrite(p1,script=script,canvas="wide")
Add watermarks to ggplots
Description
Add watermarks to ggplots
Usage
ggwater(text = "Not validated", scale = 1, rot = 30, col = "grey", alpha = 0.5)
Arguments
text |
What should be written on the plot |
scale |
the size |
rot |
rotation of the mark. Don't remember the unit. |
col |
the colour (a value, not an expression) of the watermark. Default is grey. |
alpha |
alpha value for the watermark. Default is 0.5. |
Details
This used to be based on https://www.r-bloggers.com/adding-watermarks-to-plots/ That solution stopped working, and this new solution is simpler and based on ggplot2 alone.
Value
a layer with a watermark that can be added to a plot
See Also
Other Plotting:
canvasSize(),
ggstamp(),
ggwrite()
Examples
library(ggplot2)
ff <- qplot(1:10, 11:20) + ggwater()
Export ggplot plots (and related objects) to files with stamping support
Description
Writes ggplot plots, gtable objects, or lists thereof to PNG or PDF
files with optional stamping (caption with script name, timestamp, and model information).
Supports flexible canvas sizing, multiple output formats, and both single-file and
multi-file output for lists of plots.
Usage
ggwrite(
plot,
file,
canvas = NULL,
formats,
onefile = FALSE,
res = 200,
paper = "special",
save = TRUE,
show = !save,
use.names = FALSE,
subdir = NULL,
script,
time,
model,
name.all.pdf,
quiet = FALSE,
path.format = NULL,
method.png = c("ragg", "png"),
stamp.format = NULL,
stamp.funs = NULL,
stamp.gg.style = NULL,
useNames,
fun.path = NULL
)
Arguments
plot |
A plot object or a list of plot objects. Normally generated with
|
file |
Character string specifying the output file path. Must end in
|
canvas |
Either a list with |
formats |
Character vector specifying file format(s) to write. Must be a
subset of |
onefile |
Logical. Only applicable if |
res |
Numeric. Resolution in pixels per inch for PNG output. Default is 200.
Passed to |
paper |
Character string specifying paper type. Only used with PDF device.
Default is |
save |
Logical. Should the plot be saved to file? Default is |
show |
Logical. Should the plot be displayed on screen? Default is the
opposite of |
use.names |
Logical. If |
subdir |
Character string specifying a subdirectory within the path structure.
This is passed to the path function generated from |
script |
Character string or path to the script file. If provided, a stamp
(caption) will be added to the plot showing the script name, timestamp, and
optionally the model. Requires |
time |
Character string or POSIXct timestamp. By default, a timestamp is
included if |
model |
Character string or model object specifying the model name/identifier.
Used for stamping and for organizing output directories via |
name.all.pdf |
Character string specifying the filename to use when writing
all plots to a single PDF file (when |
quiet |
Logical. If |
path.format |
Character string or function defining the output path.
A template using |
method.png |
Character string, one of |
stamp.format |
A template for the stamp text using the
placeholders |
stamp.funs |
Optional named list of functions (elements |
stamp.gg.style |
A list of formatting options for the stamp text,
passed to |
useNames |
Deprecated. Use |
fun.path |
Deprecated. Use |
Details
The function handles both single plot objects and lists of plots with flexible output options:
Single plots:
Written to
filewith specified format(s)Can generate multiple formats simultaneously
Can generate multiple canvas sizes simultaneously
Lists of plots:
If
onefile = TRUE: creates a single multi-page PDFIf
onefile = FALSE: creates separate files (numbered or named)Automatic naming based on list element names or indices
Value
Returns NULL invisibly. Files are written as a side effect.
If show = TRUE, plots are also displayed.
Canvas Sizes
Predefined canvas sizes (see canvasSize):
-
"standard": 7.2 × 5.4 inches -
"wide": 9.6 × 5.4 inches -
"wide-screen": 18.6 × 9 inches -
"square": 5.4 × 5.4 inches -
"A4": 5.4 × 7.2 inches -
"letter": 6.5 × 9 inches
Custom sizes can be specified as list(width = w, height = h) where
w and h are in inches.
Stamping
When script is provided, a caption is added to the plot using
ggstamp. The stamp typically includes:
Script file name
Timestamp (unless
time = "")Model identifier (if
modelis provided)
The stamp is added as a ggplot2 caption and will appear at the bottom of the plot.
Trace Attributes
If plot has traceit attributes (added via traceit), those
attributes will be automatically extracted and used, unless explicitly overridden
by arguments passed to ggwrite.
See Also
ggstamp for adding stamps to plots,
canvasSize for canvas size options,
writer for a unified interface to write various object types,
pathFormat for organizing output directories,
traceit for adding traceit attributes,
png, pdf for graphics devices
Other Plotting:
canvasSize(),
ggstamp(),
ggwater()
Examples
library(ggplot2)
writeOutput <- FALSE
data(ChickWeight)
p1 <- ggplot(ChickWeight, aes(Time, weight, group = Chick, colour = factor(Diet))) +
geom_line()
# View plot on screen
ggwrite(p1)
# Save plot with stamping
script <- "analysis.R"
ggwrite(p1, script = script, canvas = "wide",
file = "myplot1.png", save = writeOutput)
# Save in multiple formats
ggwrite(p1, file = "myplot1.png",
formats = c("png", "pdf"),
save = writeOutput)
# Multiple canvas sizes
ggwrite(p1, file = "myplot1.png",
canvas = list(small = "standard", large = "wide"),
save = writeOutput)
# Creates: myplot1_small.png, myplot1_large.png
# List of plots to separate files
p2 <- ggplot(ChickWeight, aes(Time, weight)) + geom_point()
plots <- list(lines = p1, points = p2)
ggwrite(plots, file = "chickweight.png",
use.names = TRUE, save = writeOutput)
# Creates: chickweight_lines.png, chickweight_points.png
# List of plots to single PDF
ggwrite(plots, file = "chickweight.pdf",
onefile = TRUE, save = writeOutput)
# Creates: chickweight.pdf (2 pages)
# Organize output using a %script-based directory structure
ggwrite(p1, file = "chickweight_lines.png",
script = script, path.format = "%script/%name",
save = writeOutput)
# Creates: analysis/chickweight_lines.png
Resolve all output file names for ggwrite
Description
Internal function that generates all combinations of file formats and canvas sizes
for ggwrite. Returns a data.table with columns: format,
name.canvas, width, height, name.file.canvas, row.
Usage
ggwrite_names(file, formats, canvas)
Arguments
file |
Character string, base file name |
formats |
Character vector of file formats ("png", "pdf") |
canvas |
Canvas size specification (see |
Value
A data.table with one row per format-canvas combination
Check if an object is a ggplot or gtable
Description
This function tests whether an object is a ggplot2 plot object or a gtable (grid table) object.
Usage
is.gg(x)
Arguments
x |
An object to test |
Value
Logical. TRUE if x inherits from "ggplot" or "gtable", FALSE otherwise.
Examples
## Not run:
library(ggplot2)
p <- ggplot(mtcars, aes(x = mpg, y = hp)) + geom_point()
is.gg(p) # TRUE
is.gg(mtcars) # FALSE
## End(Not run)
Check if an object is a list but not a plot, data frame, or flextable
Description
This function tests whether an object is a list that is NOT a ggplot/gtable, data frame, or flextable object. This is useful for identifying nested list structures that contain multiple outputs.
Usage
is.listnotplot(x)
Arguments
x |
An object to test |
Value
Logical. TRUE if x is a list but not a ggplot, gtable, data.frame, or flextable object; FALSE otherwise.
Examples
## Not run:
library(ggplot2)
p <- ggplot(mtcars, aes(x = mpg, y = hp)) + geom_point()
is.listnotplot(p) # FALSE (it's a ggplot)
is.listnotplot(mtcars) # FALSE (it's a data.frame)
is.listnotplot(list(a = 1, b = 2)) # TRUE (it's a plain list)
## End(Not run)
Write lists of outputs with flexible organization and naming
Description
Writes nested lists containing plots, tables, and data frames to files with intelligent handling of list structure, automatic naming, and optional subdirectory organization. This is particularly useful for organizing multiple related outputs from a single analysis or model run.
Usage
lwrite(
list,
model,
dir = ".",
path.format,
lists.as.subdirs = FALSE,
name.all.pdf = "main_all.pdf",
structure,
...
)
Arguments
list |
A list (potentially nested) containing output objects: |
model |
Character string or model object specifying the model name/identifier.
Used for organizing output directories and stamping. If a list (model object)
is provided, the |
dir |
Character string specifying the base output directory. Default is
|
path.format |
Character string or function defining the output path format.
Passed to |
lists.as.subdirs |
Logical. If
|
name.all.pdf |
Character string specifying the filename to use when writing
all plots to a single PDF file. Only used when the file name is empty and
plots are being combined into one PDF. Default is |
structure |
Deprecated. Use |
... |
Additional arguments passed to
|
Details
The function processes lists recursively with the following behavior:
Separates plot objects from non-plot objects
Combines plots into a single multi-page or multi-file output (see
ggwrite)Writes each non-plot object individually
Handles nested lists according to
lists.as.subdirs
Value
Invisibly returns a list of results from the writer calls.
The structure mirrors the input list structure.
List Structure Handling
The function intelligently flattens nested lists while preserving meaningful names:
Named list elements use their names in output file names
Plots in the same list are combined (behavior depends on
ggwritesettings)Non-plot objects (tables, data frames) are written individually
Nesting deeper than 2 levels will cause an error
File Naming
Output file names are constructed from:
The name at each level of the list hierarchy
The
modelidentifier (if provided and ifpath.formatuses it)Automatic numbering for unnamed elements
For example, with lists.as.subdirs = FALSE:
list(
section1 = list(
plot1 = p1,
table1 = ft1
)
)
produces: section1_plot1.png, section1_table1.png
With lists.as.subdirs = TRUE, the same structure produces:
section1/plot1.png, section1/table1.png
Plot Handling
All ggplot objects within the same list level are collected and written
together using ggwrite. This allows creating multi-page PDFs or
sequentially numbered PNG files from a list of plots.
See Also
writer for the underlying writing function,
ggwrite for plot-specific options,
ftwrite for table-specific options,
datwrite for data frame writing,
pathFormat for path format options,
is.listnotplot for list detection logic
Examples
## Not run:
library(ggplot2)
library(flextable)
# Create some outputs
p1 <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
p2 <- ggplot(mtcars, aes(hp, mpg)) + geom_point()
ft1 <- flextable(head(mtcars))
df1 <- mtcars
# Simple list
outputs <- list(
scatter_wt = p1,
scatter_hp = p2,
summary_table = ft1,
data = df1
)
lwrite(outputs, model = "run001", dir = "outputs",script="myscript")
# Creates in outputs/run001/:
# scatter_wt_run001.png
# scatter_hp_run001.png
# summary_table_run001.png
# data_run001.rds
# Nested list with subdirectories
nested_outputs <- list(
diagnostics = list(
gof1 = p1,
gof2 = p2
),
tables = list(
summary = ft1
)
)
lwrite(nested_outputs,
model = "run001",
dir = "outputs",
lists.as.subdirs = TRUE)
# Creates:
# outputs/run001/diagnostics/gof1_run001.png
# outputs/run001/diagnostics/gof2_run001.png
# outputs/run001/tables/summary_run001.png
# With stamping
lwrite(outputs,
model = "run001",
dir = "outputs",
script = "analysis.R",
time = Sys.time())
## End(Not run)
Modify a list with validation of allowed elements
Description
Internal function that combines two lists using modifyList
while validating that all element names are within a set of allowed names.
Usage
modifyListCheck(x, y, elems.allowed)
Arguments
x |
A named list with default values. |
y |
A named list with values to override those in x. Can be NULL. |
elems.allowed |
Character vector of allowed element names for both x and y. |
Details
This function first validates that x contains only allowed element names.
If y is not NULL, it merges y into x using modifyList,
then validates that the resulting list also contains only allowed names.
This ensures that both default arguments and user-provided overrides are valid.
Value
If y is NULL, returns x (after validation). Otherwise returns the result of modifyList(x, y) after validating both lists.
See Also
Pad Numbers with Leading Zeros
Description
Converts numeric values to character strings with leading zeros to achieve a specified total width.
Usage
padZeros(x, nchars)
Arguments
x |
A numeric vector of integers to be padded with leading zeros. |
nchars |
An integer specifying the total number of characters in the output string (including leading zeros). |
Value
A character vector of the same length as x, with each element
padded with leading zeros to reach nchars characters.
Examples
# Pad single digit numbers to 3 characters
padZeros(5, 3)
# Returns: "005"
# Pad a vector of numbers
padZeros(c(1, 10, 100), 4)
# Returns: c("0001", "0010", "0100")
# Useful for creating sequential file names
paste0("file_", padZeros(1:5, 3), ".txt")
# Returns: c("file_001.txt", "file_002.txt", ..., "file_005.txt")
# Or append to an existing file name
NMdata::fnAppend("file.txt", padZeros(1:5, 3), collapse=NULL)
Create a function to derive output file paths from a path format
Description
Generates a function that constructs file paths according to a path format (a template with placeholders). This is particularly useful in modeling workflows where outputs need to be organized by model name, with consistent naming conventions across files.
Usage
pathFormat(
path.format = "%name",
dir,
model = NULL,
script = NULL,
path.funs = NULL,
structure
)
Arguments
path.format |
A character string specifying a path format template, or a custom function. If a function is provided, it is returned without modification. Templates are specified using
Any other combination of |
dir |
Character string specifying the base directory for all outputs. This is
prepended to all generated paths. Default is |
model |
Default value for the |
script |
Default value for the |
path.funs |
Optional named list of functions used to preprocess
|
structure |
Deprecated. Use |
Details
The returned function accepts the following arguments:
nameThe base file name (typically without extension)
modelA model identifier (character string or model object). If a model object (list) is provided, the
$modelement is extracted and used as the model name. The file extension is automatically removed from the model name (e.g., "model.lst" becomes "model").scriptA script identifier (character string, typically a script file name). The file extension is automatically removed (e.g., "myscript.R" becomes "myscript").
subdirOptional subdirectory. Inserted between the directory components of
path.formatand the file name component.dirBase directory. Overrides the
dirargument passed topathFormat.quietIf
TRUE, suppress messages about ignoredmodel/scriptarguments. DefaultFALSE.
The generated function handles missing model/script arguments
gracefully - if path.format does not contain %model (or
%script), the corresponding argument is optional and ignored (with a
message if supplied anyway). If path.format does contain %model
(or %script), the corresponding argument is required.
Value
A function with signature function(name, model, script, subdir, dir, quiet = FALSE) that
generates file paths according to the specified path format. If path.format
is already a function, it is returned unchanged.
See Also
writer for using path formats in writing functions,
ggwrite, ftwrite, lwrite for functions
that accept fun.path arguments
Examples
# Create a path function (default format)
path_fun <- pathFormat(path.format = "%model/%name_%model")
# Use it to generate paths
path_fun(name = "gof1.png", model = "run001")
# Returns: "run001/gof1_run001.png"
path_fun(name = "gof1.png", model = "run001", subdir = "diagnostics")
# Returns: "run001/diagnostics/gof1_run001.png"
# With base directory
path_fun2 <- pathFormat(path.format = "%model/%model-%name", dir = "outputs")
path_fun2(name = "gof1.png", model = "run001")
# Returns: "outputs/run001/run001-gof1.png"
# Different format
path_fun3 <- pathFormat(path.format = "%model-%name")
path_fun3(name = "gof1.png", model = "run001")
# Returns: "run001-gof1.png"
# Fully custom format
path_fun3b <- pathFormat(path.format = "archive/%model/plots/%name")
path_fun3b(name = "gof1.png", model = "run001")
# Returns: "archive/run001/plots/gof1.png"
# Format based on script name
path_fun3c <- pathFormat(path.format = "%script/%name_%model")
path_fun3c(name = "gof1.png", model = "run001", script = "myscript")
# Returns: "myscript/gof1_run001.png"
# Supplying default model/script to pathFormat() itself
path_fun3d <- pathFormat(path.format = "%script/%name_%model",
model = "run001", script = "myscript")
path_fun3d(name = "gof1.png")
# Returns: "myscript/gof1_run001.png"
# Explicit arguments to the generated function override the defaults
path_fun3d(name = "gof1.png", model = "run002")
# Returns: "myscript/gof1_run002.png"
# Custom preprocessing of script (and/or model) via path.funs
path_fun3e <- pathFormat(path.format = "%script/%name_%model",
path.funs = list(script = function(x) substr(basename(x), 1, 4)))
path_fun3e(name = "gof1.png", model = "run001", script = "myscript.R")
# Returns: "mysc/gof1_run001.png"
# Custom function (passed through unchanged)
my_fun <- function(name, model, subdir) {
paste0("custom/", model, "/", name)
}
path_fun4 <- pathFormat(path.format = my_fun)
identical(path_fun4, my_fun) # TRUE
Deprecated: use pathFormat()
Description
pathStruct() is deprecated. Use pathFormat.
Usage
pathStruct(...)
Arguments
... |
Passed to |
Value
See pathFormat.
Print a plot or gtable object to the current device
Description
Internal helper that dispatches to the correct printing mechanism depending
on the class of plot. gtable objects (e.g. from
grid.arrange) must be drawn with
grid.draw, while other objects (e.g. ggplot) use
the standard print method. NULL input is silently ignored.
Usage
print1(plot)
Arguments
plot |
A plot object ( |
Value
NULL, invisibly. Called for the side effect of drawing to
the current device.
Stamp and write flextab objects (deprecated - use ftstamp)
Description
Deprecated - use ftstamp() instead.
Usage
stampFlextab(ft, file, script, bg = "#ffffff", time)
Arguments
ft |
a flextable object |
file |
The file that the flextable will be written to (no file is written by this function) |
script |
path to script - will be pasted as caption. |
bg |
Default bacground colour is #ffffff. |
time |
The default is to insert a time stamp taken from result of Sys.time(). Using the time argument you can overrule this by setting a fixed string instead. Use "" to omit. |
Value
A flextable object with the stamp added as a footer line.
Create a stamp grob with independent placement and line justification
Description
Create a stamp grob with independent placement and line justification
Usage
stampGrob(caption, pos = 1, style = list(), hjust = NULL, gp = NULL)
Arguments
caption |
The stamp text. |
pos |
Placement of the text block (0=left, 1=right). |
style |
element_text-like list (size, colour, hjust, family, face, lineheight). Ignored if gp given. |
hjust |
Line justification within the block. Taken from style if NULL. |
gp |
A gpar object. If NULL, derived from style. |
Value
A grob
Translate a stamp position to a numeric value between 0 and 1
Description
Translate a stamp position to a numeric value between 0 and 1
Usage
stampPosition(position)
Arguments
position |
"left", "center", "right" or a number between 0 and 1. NULL means "right". |
Value
numeric
Add tracing attributes to R objects for automated output writing
Description
The traceit family of functions attaches metadata to R objects that can be
used later by writer functions to automatically determine output settings. This
allows you to "trace" or "tag" objects with information about how they should be
written, then write them later without having to re-specify those settings.
Usage
traceit(x, ...)
## S3 method for class 'ggplot'
traceit(x, ..., quite = TRUE)
## S3 method for class 'flextable'
traceit(x, ..., quite = TRUE)
## S3 method for class 'data.frame'
traceit(x, ..., quite = TRUE)
## S3 method for class 'traceit'
traceit(x, ..., quite = TRUE)
Arguments
x |
An R object to attach trace attributes to. Can be a |
... |
Named arguments that will be stored as trace attributes. For ggplot
objects, valid arguments match those in |
quite |
Logical. If |
Details
The traceit function is a generic that dispatches to specific methods based
on the class of x:
-
traceit.ggplot: For ggplot objects -
traceit.flextable: For flextable objects -
traceit.data.frame: For data frames -
traceit.traceit: For objects that already have traceit attributes (allows updating existing trace information)
When an object is traced, two attributes are added:
-
args: A list of arguments to be used when writing the object -
class: The class vector is prepended with "traceit" to indicate the object has been traced
Arguments passed to traceit are filtered to include only those that are
valid for the corresponding writer function. Invalid arguments are silently ignored.
When calling traceit on an already-traced object, the new arguments are
merged with existing trace arguments using modifyList, with
new arguments taking precedence.
Value
Returns x invisibly with trace attributes attached. The object
can be used normally and the trace attributes will be preserved.
Extracting Trace Attributes
To extract trace attributes from an object, use argsFromTrace.
See Also
ggwrite for writing ggplot objects,
ftwrite for writing flextable objects,
NMwriteData for writing data frames,
argsFromTrace for extracting trace attributes,
writer for a unified writing interface
Examples
## Not run:
library(ggplot2)
library(flextable)
# Create a plot and trace it with output settings
p1 <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
p1_traced <- traceit(p1, canvas = "wide", formats = c("png", "pdf"))
# The traced plot can be written later without re-specifying settings
# writer() will automatically use the traced arguments
# Trace a flextable
ft1 <- flextable(head(mtcars))
ft1_traced <- traceit(ft1, formats = "docx")
# Update trace attributes on an already-traced object
p1_traced <- traceit(p1_traced, canvas = "standard") # overrides previous canvas
# Trace a data frame for NMwriteData
df1 <- data.frame(ID = 1:10, DV = rnorm(10))
df1_traced <- traceit(df1, file = "mydata.csv")
## End(Not run)
Determine the class type of an R object for writer dispatch
Description
Internal function that determines the appropriate class type of an object for dispatching to the correct writer function. This function classifies objects into one of several categories: "flextable", "data.frame", "gg" (for ggplot/gtable objects), "list", or throws an error for unknown types.
Usage
trclass(x)
Arguments
x |
An R object to classify. Can be a |
Details
The function checks object class in the following priority order:
-
flextable: checked via"flextable" %in% class(x) -
data.frame: checked viais.data.frame(x) -
gg: checked viais.gg(x)(includes ggplot and gtable) -
list: checked viais.list(x) && !is.gg(x) If none match: throws an error
This function is primarily used internally by writer and
traceit.traceit to determine which specific writer function
to call (ggwrite, ftwrite, or datwrite).
The function ignores the "traceit" class that may be prepended by
traceit, allowing it to classify traced objects by their
underlying type.
Value
A character string indicating the object class type:
-
"flextable": for flextable objects -
"data.frame": for data frame objects -
"gg": for ggplot or gtable objects -
"list": for list objects (that are not plots)
See Also
writer for the main writer function that uses this classification,
traceit.traceit for traceit method that uses this,
is.gg for plot object detection,
is.listnotplot for list detection logic
Examples
## Not run:
library(ggplot2)
library(flextable)
# Classify different object types
trclass(mtcars) # Returns: "data.frame"
p1 <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
trclass(p1) # Returns: "gg"
ft1 <- flextable(head(mtcars))
trclass(ft1) # Returns: "flextable"
trclass(list(p1, ft1)) # Returns: "list"
# Works with traced objects too
p1_traced <- traceit(p1, canvas = "wide")
trclass(p1_traced) # Still returns: "gg"
# Unknown types throw an error
trclass(matrix(1:4, 2)) # Error: x is an unknown format
## End(Not run)
Remove traceit information from an object
Description
Removes the args attribute and the "traceit" class
added by traceit. The object is modified in place.
Usage
untraceit(x)
Arguments
x |
An object |
Value
x without traceit information (invisibly)
Write a single plot to a single file (or display it)
Description
Internal function that performs the actual device handling (opening a
png/agg_png or
pdf device, printing the plot, and closing the
device) for a single plot/file/size combination. Also applies stamping via
ggstamp before printing. If fn or type indicate
on-screen display ("x11"), the plot is printed directly without opening a
file device.
Usage
write1(
plot,
fn = NULL,
type = NULL,
onefile = FALSE,
size,
script,
time,
model,
quiet = FALSE,
subdir = NULL,
method.png = c("ragg", "png"),
fun.path = NULL,
stamp.format = NULL,
stamp.funs = NULL,
stamp.gg.style = NULL,
...
)
Arguments
plot |
A single plot object ( |
fn |
Character string, output file name (without or with extension;
the extension is replaced/added based on |
type |
Character string, one of |
onefile |
Logical, passed to the |
size |
A list with |
script |
Character string or path to the calling script, used for
stamping. See |
time |
Character string or POSIXct timestamp used for stamping. |
model |
Character string or model object used for stamping and path construction. |
quiet |
Logical. If |
subdir |
Character string, subdirectory passed on to |
method.png |
Character string, one of |
fun.path |
Function or character string defining output directory
structure, applied to |
stamp.format, stamp.funs, stamp.gg.style |
Passed to |
... |
Additional arguments. |
Value
NULL, invisibly. Called for the side effect of writing a file
and/or displaying the plot.
See Also
Write a plot or list of plots to one or more files
Description
Internal workhorse function called by ggwrite. Resolves the
combination of output formats and canvas sizes (via ggwrite_names),
and dispatches to write1 for each individual plot/format/canvas
combination. Handles both single plot objects and lists of plots, including
the onefile (multi-page PDF) case.
Usage
writeObj(
plot,
file,
script,
time,
model = model,
onefile,
use.names = FALSE,
formats,
canvas,
quiet = FALSE,
fun.path,
subdir,
name.all.pdf = "all.pdf",
method.png = c("ragg", "png"),
...
)
Arguments
plot |
A plot object or a list of plot objects. See |
file |
Character string, base output file path, or |
script |
Character string or path to the calling script, used for stamping.
See |
time |
Character string or POSIXct timestamp used for stamping. |
model |
Character string or model object used for stamping and path construction. |
onefile |
Logical. If |
use.names |
Logical. If |
formats |
Character vector of file formats, a subset of |
canvas |
Canvas size specification. See |
quiet |
Logical. If |
fun.path |
Function or character string defining output directory structure.
See |
subdir |
Character string, subdirectory passed on to |
name.all.pdf |
Character string, file name to use for a combined multi-page
PDF when |
method.png |
Character string, one of |
... |
Value
NULL, invisibly. Files are written (and/or plots displayed) as
a side effect.
See Also
ggwrite, write1, ggwrite_names
Write various R objects to files with flexible formatting
Description
A unified interface for ggwrite, ftwrite, and
NMwriteData that automatically detects object type and
applies the appropriate writing function with consistent file naming and
stamping conventions.
Usage
writer(
x,
file,
formats.ft,
formats.gg,
formats.data,
path.format = NULL,
subdir = NULL,
stamp.format = NULL,
stamp.funs = NULL,
stamp.gg.style = NULL,
stamp.ft.style = NULL,
fun.path = NULL,
...
)
Arguments
x |
Object to write. Can be a |
file |
Character string specifying the base file name (without extension).
The actual extension will be determined by the |
formats.ft |
Character vector of file formats for flextable objects.
Default is |
formats.gg |
Character vector of file formats for ggplot objects.
Default is |
formats.data |
Character vector of file formats for data frame objects.
Default is |
path.format |
Character string or function defining the output path.
A template using |
subdir |
Character string specifying a subdirectory within the path structure.
This is passed to the path function generated from |
stamp.format |
A template for the stamp text using the
placeholders |
stamp.funs |
Optional named list of functions (elements |
stamp.gg.style |
A list of formatting options for the stamp text,
passed to |
stamp.ft.style |
A list of formatting options for the stamp,
passed to |
fun.path |
Deprecated. Use |
... |
Additional arguments passed to the specific writer functions
(
|
Details
The function dispatches to appropriate writer functions based on object class:
-
flextableobjects →ftwrite -
data.frameobjects →datwrite(which wrapsNMwriteData) -
ggplot/gtableobjects or lists →ggwrite
For lists of objects, each element is written separately with appropriate naming. The function intelligently handles nested lists by flattening them and constructing meaningful file names from the list structure.
File paths are constructed using path.format, which can organize
outputs by model, file name, or custom patterns. This is particularly useful in
modeling workflows where outputs need to be organized by model number or name.
Value
Invisibly returns the result from the called writer function. The specific return value depends on which writer function was dispatched to.
Object Type Detection
The function determines object type in the following order:
Check if
flextableCheck if
data.frameCheck if
ggplotorgtable(usingis.gg)Check if
list(and not a plot object)If none of the above, throw an error
Trace Attributes
If the object x has traceit attributes (added via traceit),
those attributes will be automatically extracted and used by the writer function,
unless explicitly overridden by arguments passed to writer.
See Also
ggwrite for writing ggplot objects,
ftwrite for writing flextable objects,
datwrite for writing data frames,
lwrite for writing lists with subdirectory organization,
pathFormat for path format options,
traceit for adding traceit attributes to objects
Examples
## Not run:
library(ggplot2)
library(flextable)
# Write a ggplot
p1 <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
writer(p1, file = "myplot", formats.gg = c("png", "pdf"))
# Write a flextable
ft1 <- flextable(head(mtcars))
writer(ft1, file = "mytable", formats.ft = c("png", "docx"))
# Write a data frame
writer(mtcars, file = "mydata", formats.data = "csv")
# Use with model organization
writer(p1, file = "gof", model = "run001", path.format = "%model/%name_%model")
# Writes to: run001/gof_run001.png
# Write with stamping
writer(p1, file = "myplot",
script = "analysis.R",
time = Sys.time(),
model = "run001")
## End(Not run)