Title: | ASCII Formatting for Values and Tables |
Version: | 0.5.11 |
Date: | 2025-04-08 |
Description: | We provide a framework for rendering complex tables to ASCII, and a set of formatters for transforming values or sets of values into ASCII-ready display strings. |
License: | Apache License 2.0 |
URL: | https://insightsengineering.github.io/formatters/, https://github.com/insightsengineering/formatters/ |
BugReports: | https://github.com/insightsengineering/formatters/issues |
Depends: | methods, R (≥ 2.10) |
Imports: | checkmate (≥ 2.1.0), grid, htmltools (≥ 0.5.3), lifecycle (≥ 0.2.0), stringi (≥ 1.7.12) |
Suggests: | dplyr (≥ 1.0.9), gt (≥ 0.10.0), huxtable (≥ 2.0.0), knitr (≥ 1.42), r2rtf (≥ 0.3.2), rmarkdown (≥ 2.23), testthat (≥ 3.0.4), withr (≥ 2.0.0) |
VignetteBuilder: | knitr, rmarkdown |
Config/Needs/verdepcheck: | mllg/checkmate, rstudio/htmltools, r-lib/lifecycle, tidyverse/dplyr, rstudio/gt, hughjonesd/huxtable, yihui/knitr, Merck/r2rtf, rstudio/rmarkdown, gagolews/stringi, r-lib/testthat, r-lib/withr |
Config/Needs/website: | insightsengineering/nesttemplate |
Encoding: | UTF-8 |
Language: | en-US |
LazyData: | true |
RoxygenNote: | 7.3.2 |
Collate: | 'data.R' 'format_value.R' 'matrix_form.R' 'generics.R' 'labels.R' 'mpf_exporters.R' 'package.R' 'page_size.R' 'pagination.R' 'tostring.R' 'utils.R' 'zzz.R' |
NeedsCompilation: | no |
Packaged: | 2025-04-08 20:38:39 UTC; melkiades |
Author: | Gabriel Becker [aut] (original creator of the package),
Adrian Waddell [aut],
Davide Garolini |
Maintainer: | Joe Zhu <joe.zhu@roche.com> |
Repository: | CRAN |
Date/Publication: | 2025-04-09 09:40:22 UTC |
formatters Package
Description
Package to format tables and listings in a flexible way.
Author(s)
Maintainer: Joe Zhu joe.zhu@roche.com (ORCID)
Authors:
Gabriel Becker gabembecker@gmail.com (original creator of the package)
Adrian Waddell adrian.waddell@gene.com
Davide Garolini davide.garolini@roche.com (ORCID)
Emily de la Rua emily.de_la_rua@contractors.roche.com (ORCID)
Other contributors:
Abinaya Yogasekaram abinaya.yogasekaram@contractors.roche.com (ORCID) [contributor]
F. Hoffmann-La Roche AG [copyright holder, funder]
See Also
Useful links:
Report bugs at https://github.com/insightsengineering/formatters/issues
DM data
Description
DM data
Usage
DM
Format
rds
(data.frame
)
Constructor for Matrix Print Form
Description
Constructor for MatrixPrintForm
, an intermediate representation for ASCII table printing.
Usage
MatrixPrintForm(
strings = NULL,
spans,
aligns,
formats,
row_info,
colpaths = NULL,
line_grouping = seq_len(NROW(strings)),
ref_fnotes = list(),
nlines_header,
nrow_header,
has_topleft = TRUE,
has_rowlabs = has_topleft,
expand_newlines = TRUE,
main_title = "",
subtitles = character(),
page_titles = character(),
listing_keycols = NULL,
main_footer = "",
prov_footer = character(),
header_section_div = NA_character_,
horizontal_sep = default_hsep(),
col_gap = 3,
table_inset = 0L,
colwidths = NULL,
indent_size = 2,
fontspec = font_spec(),
rep_cols = 0L
)
Arguments
strings |
( |
spans |
( |
aligns |
( |
formats |
( |
row_info |
( |
colpaths |
( |
line_grouping |
( |
ref_fnotes |
( |
nlines_header |
( |
nrow_header |
( |
has_topleft |
( |
has_rowlabs |
( |
expand_newlines |
( |
main_title |
( |
subtitles |
( |
page_titles |
( |
listing_keycols |
( |
main_footer |
( |
prov_footer |
( |
header_section_div |
( |
horizontal_sep |
( |
col_gap |
( |
table_inset |
( |
colwidths |
( |
indent_size |
( |
fontspec |
( |
rep_cols |
( |
Value
An object of class MatrixPrintForm
. Currently this is implemented as an S3 class inheriting
from list with the following elements:
strings
see argument.
spans
see argument.
aligns
see argument.
display
logical matrix of same dimension as
strings
that specifies whether an element instrings
will be displayed when the table is rendered.formats
see argument.
row_info
see argument.
line_grouping
see argument.
ref_footnotes
see argument.
main_title
see argument.
subtitles
see argument.
page_titles
see argument.
main_footer
see argument.
prov_footer
see argument.
header_section_div
see argument.
horizontal_sep
see argument.
col_gap
see argument.
table_inset
see argument.
as well as the following attributes:
nlines_header
see argument.
nrow_header
see argument.
ncols
number of columns of the table, not including any row names/row labels
Note
The bare constructor for the MatrixPrintForm
should generally
only be called by matrix_form
custom methods, and almost never from other code.
Examples
basic_matrix_form(iris) # calls matrix_form which calls this constructor
Class for Matrix Print Form
Description
The MatrixPrintForm
class, an intermediate representation for ASCII table printing.
Basic/spoof pagination info data frame
Description
Returns a minimal pagination info data.frame
(with no info on siblings, footnotes, etc.).
Usage
basic_pagdf(
rnames,
labs = rnames,
rnums = seq_along(rnames),
extents = 1L,
rclass = "DataRow",
parent_path = NULL,
paths = lapply(rnames, function(x) c(parent_path, x)),
fontspec = font_spec()
)
Arguments
rnames |
( |
labs |
( |
rnums |
( |
extents |
( |
rclass |
( |
parent_path |
( |
paths |
( |
fontspec |
( |
Value
A data.frame
suitable for use in both the MatrixPrintForm
constructor and the pagination machinery.
Examples
basic_pagdf(c("hi", "there"))
Check if a format or alignment is supported
Description
Utility functions for checking formats and alignments.
Usage
is_valid_format(x, stop_otherwise = FALSE)
check_aligns(algn)
Arguments
x |
( |
stop_otherwise |
( |
algn |
( |
Value
-
is_valid_format
returnsTRUE
ifx
isNULL
, a supported format string, or a function, andFALSE
otherwise.
-
check_aligns
returnsTRUE
if the provided alignments are supported, otherwise, an error is thrown.
Note
If x
is a function, no check is performed to verify that it returns a valid format.
Examples
is_valid_format("xx.x")
is_valid_format("fakeyfake")
check_aligns(c("decimal", "dec_right"))
Decimal alignment
Description
Aligning decimal values of string matrix. Allowed alignments are: dec_left
, dec_right
,
and decimal
.
Usage
decimal_align(string_mat, align_mat)
Arguments
string_mat |
( |
align_mat |
( |
Details
Left and right decimal alignment (dec_left
and dec_right
) differ from center decimal
alignment (decimal
) only when there is padding present. This may occur if column widths are
set wider via parameters widths
in toString
or colwidths
in paginate_*
. More commonly,
it also occurs when column names are wider. Cell wrapping is not supported when decimal
alignment is used.
Value
A processed string matrix of class MatrixPrintForm
with decimal-aligned values.
See Also
Examples
dfmf <- basic_matrix_form(mtcars[1:5, ])
aligns <- mf_aligns(dfmf)
aligns[, -c(1)] <- "dec_left"
decimal_align(mf_strings(dfmf), aligns)
Default horizontal separator
Description
The default horizontal separator character which can be displayed in the current charset for use in rendering table-like objects.
The default horizontal separator character which can be displayed in the current charset for use in rendering table-like objects.
Usage
default_hsep()
set_default_hsep(hsep_char)
default_hsep()
set_default_hsep(hsep_char)
Arguments
hsep_char |
( |
Value
unicode 2014 (long dash for generating solid horizontal line) if in a locale that uses a UTF character set, otherwise an ASCII hyphen with a once-per-session warning.
unicode 2014 (long dash for generating solid horizontal line) if in a locale that uses a UTF character set, otherwise an ASCII hyphen with a once-per-session warning.
Examples
default_hsep()
set_default_hsep("o")
default_hsep()
default_hsep()
set_default_hsep("o")
default_hsep()
Default page number format
Description
If set, the default page number string will appear on the bottom right of
every page of a paginated table. The current cpp
is used to position the string.
Usage
default_page_number()
set_default_page_number(page_number)
Arguments
page_number |
( |
Value
The page number format string (NULL
if not set).
Examples
default_page_number()
set_default_page_number("page {i} of {n}")
default_page_number()
Divider height
Description
Divider height
Usage
divider_height(obj)
## S4 method for signature 'ANY'
divider_height(obj)
Arguments
obj |
( |
Value
The height, in lines of text, of the divider between header and body. Currently
returns 1L
for the default method.
Examples
divider_height(mtcars)
Generic for performing "forced" pagination
Description
Forced pagination is pagination which happens regardless of position on page. The object
is expected to have all information necessary to locate such page breaks, and the
do_forced_pag
method is expected to fully perform those paginations.
Usage
do_forced_paginate(obj)
## S4 method for signature 'ANY'
do_forced_paginate(obj)
Arguments
obj |
( |
Value
A list of sub-objects, which will be further paginated by the standard pagination algorithm.
Simulated CDISC-like data for examples
Description
Simulated CDISC-like data for examples
Usage
ex_adsl
ex_adae
ex_adaette
ex_adtte
ex_adcm
ex_adlb
ex_admh
ex_adqs
ex_adrs
ex_advs
Format
rds
(data.frame
)
An object of class tbl_df
(inherits from tbl
, data.frame
) with 1934 rows and 48 columns.
An object of class tbl_df
(inherits from tbl
, data.frame
) with 1200 rows and 42 columns.
An object of class tbl_df
(inherits from tbl
, data.frame
) with 1200 rows and 42 columns.
An object of class tbl_df
(inherits from tbl
, data.frame
) with 1934 rows and 41 columns.
An object of class tbl_df
(inherits from tbl
, data.frame
) with 8400 rows and 59 columns.
An object of class tbl_df
(inherits from tbl
, data.frame
) with 1934 rows and 41 columns.
An object of class tbl_df
(inherits from tbl
, data.frame
) with 14000 rows and 49 columns.
An object of class tbl_df
(inherits from tbl
, data.frame
) with 2400 rows and 41 columns.
An object of class tbl_df
(inherits from tbl
, data.frame
) with 16800 rows and 59 columns.
Export as PDF
Description
The PDF output from this function is based on the ASCII output created with toString()
.
Usage
export_as_pdf(
x,
file,
page_type = "letter",
landscape = FALSE,
pg_width = page_dim(page_type)[if (landscape) 2 else 1],
pg_height = page_dim(page_type)[if (landscape) 1 else 2],
width = lifecycle::deprecated(),
height = lifecycle::deprecated(),
margins = c(4, 4, 4, 4),
min_siblings = 2,
font_family = "Courier",
font_size = 8,
fontsize = font_size,
lineheight = 1.2,
paginate = TRUE,
page_num = default_page_number(),
lpp = NULL,
cpp = NULL,
hsep = "-",
indent_size = 2,
rep_cols = NULL,
tf_wrap = TRUE,
max_width = NULL,
colwidths = NULL,
fontspec = font_spec(font_family, font_size, lineheight),
ttype_ok = FALSE,
round_type = c("iec", "sas")
)
Arguments
x |
( |
file |
( |
page_type |
( |
landscape |
( |
pg_width |
( |
pg_height |
( |
width |
|
height |
|
margins |
( |
min_siblings |
( |
font_family |
( |
font_size |
( |
fontsize |
|
lineheight |
( |
paginate |
( |
page_num |
( |
lpp |
( |
cpp |
( |
hsep |
( |
indent_size |
( |
rep_cols |
( |
tf_wrap |
( |
max_width |
( |
colwidths |
( |
fontspec |
( |
ttype_ok |
( |
round_type |
( |
Details
By default, pagination is performed with default cpp
and lpp
defined by specified page
dimensions and margins. User-specified lpp
and cpp
values override this, and should
be used with caution.
Title and footer materials are also word-wrapped by default (unlike when printed to the
terminal), with cpp
(as defined above) as the default max_width
.
See Also
Examples
## Not run:
tf <- tempfile(fileext = ".pdf")
export_as_pdf(basic_matrix_form(mtcars), file = tf, pg_height = 4)
tf <- tempfile(fileext = ".pdf")
export_as_pdf(basic_matrix_form(mtcars), file = tf, lpp = 8)
## End(Not run)
Export as RTF
Description
Experimental export to the rich text format (RTF) format.
Usage
export_as_rtf(
x,
file = NULL,
colwidths = NULL,
page_type = "letter",
pg_width = page_dim(page_type)[if (landscape) 2 else 1],
pg_height = page_dim(page_type)[if (landscape) 1 else 2],
landscape = FALSE,
margins = c(bottom = 0.5, left = 0.75, top = 0.5, right = 0.75),
font_family = "Courier",
font_size = 8,
lineheight = 1,
fontspec = font_spec(font_family, font_size, lineheight),
paginate = TRUE,
...
)
Arguments
x |
( |
file |
( |
colwidths |
( |
page_type |
( |
pg_width |
( |
pg_height |
( |
landscape |
( |
margins |
( |
font_family |
( |
font_size |
( |
lineheight |
( |
fontspec |
( |
paginate |
( |
... |
additional parameters passed to |
Details
RTF export occurs via the following steps:
The table is paginated to the specified page size (vertically and horizontally).
Each separate page is converted to a
MatrixPrintForm
object and then to RTF-encoded text.Separate RTF text chunks are combined and written to a single RTF file.
Conversion of MatrixPrintForm
objects to RTF is done via mpf_to_rtf()
.
Export a table-like object to plain (ASCII) text with page breaks
Description
This function converts x
to a MatrixPrintForm
object via matrix_form()
, paginates it
via paginate_to_mpfs()
, converts each page to ASCII text via toString()
, and outputs
the strings, separated by page_break
, to file
.
Usage
export_as_txt(
x,
file = NULL,
page_type = NULL,
landscape = FALSE,
pg_width = page_dim(page_type)[if (landscape) 2 else 1],
pg_height = page_dim(page_type)[if (landscape) 1 else 2],
font_family = "Courier",
font_size = 8,
lineheight = 1L,
margins = c(top = 0.5, bottom = 0.5, left = 0.75, right = 0.75),
paginate = TRUE,
cpp = NA_integer_,
lpp = NA_integer_,
...,
hsep = NULL,
indent_size = 2,
tf_wrap = paginate,
max_width = NULL,
colwidths = NULL,
min_siblings = 2,
nosplitin = character(),
rep_cols = NULL,
verbose = FALSE,
page_break = "\\s\\n",
page_num = default_page_number(),
fontspec = font_spec(font_family, font_size, lineheight),
col_gap = 3,
round_type = c("iec", "sas")
)
Arguments
x |
( |
file |
( |
page_type |
( |
landscape |
( |
pg_width |
( |
pg_height |
( |
font_family |
( |
font_size |
( |
lineheight |
( |
margins |
( |
paginate |
( |
cpp |
( |
lpp |
( |
... |
additional parameters passed to |
hsep |
( |
indent_size |
( |
tf_wrap |
( |
max_width |
( |
colwidths |
( |
min_siblings |
( |
nosplitin |
( |
rep_cols |
( |
verbose |
( |
page_break |
( |
page_num |
( |
fontspec |
( |
col_gap |
( |
round_type |
( |
Details
If x
has a num_rep_cols
method, the value returned by it will be used for rep_cols
by
default. Otherwise, 0 will be used.
If x
has an applicable do_forced_paginate
method, it will be invoked during the
pagination process.
Value
If file
is NULL
, the full paginated and concatenated string value is returned,
otherwise the output is written to file
and no value (invisible NULL
) is returned.
Examples
export_as_txt(basic_matrix_form(mtcars), pg_height = 5, pg_width = 4)
Format configuration
Description
Format configuration
Usage
fmt_config(format = NULL, na_str = "NA", align = "center")
Arguments
format |
( |
na_str |
( |
align |
( |
Value
An object of class fmt_config
which contains the following elements:
-
format
-
na_str
-
align
Examples
fmt_config(format = "xx.xx", na_str = "-", align = "left")
fmt_config(format = "xx.xx - xx.xx", align = "right")
Calculate lines per inch and characters per inch for font
Description
Calculate lines per inch and characters per inch for font
Usage
font_lcpi(
font_family = "Courier",
font_size = 8,
lineheight = 1,
fontspec = font_spec(font_family, font_size, lineheight)
)
Arguments
font_family |
( |
font_size |
( |
lineheight |
( |
fontspec |
( |
Details
This function opens a PDF graphics device, writes to a temporary file, then
utilizes grid::convertWidth()
and grid::convertHeight()
to calculate lines
per inch and characters per inch for the specified font family, size, and
line height.
An error is thrown if the font is not monospaced (determined by comparing
the effective widths of the M
and .
glyphs).
Value
A named list with cpi
and lpi
, the characters and lines per
inch, respectively.
Examples
font_lcpi <- getFromNamespace("font_lcpi", "formatters")
font_lcpi()
font_lcpi(font_size = 8)
font_lcpi(font_size = 8, lineheight = 1.1)
Font size specification
Description
Font size specification
Usage
font_spec(font_family = "Courier", font_size = 8, lineheight = 1)
Arguments
font_family |
( |
font_size |
( |
lineheight |
( |
Details
Passing the output of this constructor to the rendering or pagination machinery defines a font for use when calculating word wrapping and pagination.
Note
Specifying font in this way to, e.g., export_as_txt()
or
toString()
will not affect the font size of the output, as these
are both raw text formats. export_as_pdf()
will use the specified font.
See Also
nchar_ttype()
, toString()
, pagination_algo
, export_as_pdf()
Examples
fspec <- font_spec("Courier", 8, 1)
lets <- paste(letters, collapse = "")
nchar_ttype(lets, fspec)
fspec2 <- font_spec("Times", 8, 1)
nchar_ttype(lets, fspec2)
Converts a (possibly compound) value into a string using the format
information
Description
Converts a (possibly compound) value into a string using the format
information
Usage
format_value(
x,
format = NULL,
output = c("ascii", "html"),
na_str = "NA",
round_type = c("iec", "sas")
)
Arguments
x |
( |
format |
( |
output |
( |
na_str |
( |
round_type |
( |
Details
A length-zero value for na_str
will be interpreted as "NA"
.
Value
Formatted text representing the cell x
.
See Also
Examples
x <- format_value(pi, format = "xx.xx")
x
format_value(x, output = "ascii")
# na_str works with multiple values
format_value(c(NA, 1, NA), format = "xx.x (xx.x - xx.x)", na_str = c("NE", "<missing>"))
%||%
(if length-0) alternative operator
Description
%||%
(if length-0) alternative operator
Usage
a %||% b
Arguments
a |
( |
b |
( |
Value
a
if it is not of length 0, otherwise b
.
Examples
6 %||% 10
character() %||% "hi"
NULL %||% "hi"
Check if a value is a whole number
Description
Check if a value is a whole number
Usage
is.wholenumber(x, tol = .Machine$double.eps^0.5)
Arguments
x |
( |
tol |
( |
Value
TRUE
if x
is within tol
of zero, FALSE
otherwise.
Examples
is.wholenumber(5)
is.wholenumber(5.00000000000000001)
is.wholenumber(.5)
Label, name, and format accessor generics
Description
Getters and setters for basic, relatively universal attributes of "table-like" objects.
Usage
obj_name(obj)
obj_name(obj) <- value
obj_label(obj)
obj_label(obj) <- value
## S4 method for signature 'ANY'
obj_label(obj)
## S4 replacement method for signature 'ANY'
obj_label(obj) <- value
obj_format(obj)
## S4 method for signature 'ANY'
obj_format(obj)
## S4 method for signature 'fmt_config'
obj_format(obj)
obj_format(obj) <- value
## S4 replacement method for signature 'ANY'
obj_format(obj) <- value
## S4 replacement method for signature 'fmt_config'
obj_format(obj) <- value
obj_na_str(obj)
## S4 method for signature 'ANY'
obj_na_str(obj)
## S4 method for signature 'fmt_config'
obj_na_str(obj)
obj_na_str(obj) <- value
## S4 replacement method for signature 'ANY'
obj_na_str(obj) <- value
## S4 replacement method for signature 'fmt_config'
obj_na_str(obj) <- value
obj_align(obj)
## S4 method for signature 'ANY'
obj_align(obj)
## S4 method for signature 'fmt_config'
obj_align(obj)
obj_align(obj) <- value
## S4 replacement method for signature 'ANY'
obj_align(obj) <- value
## S4 replacement method for signature 'fmt_config'
obj_align(obj) <- value
Arguments
obj |
( |
value |
character(1). The new label |
Value
The name, format, or label of obj
for getters, or obj
after modification for setters.
See Also
with_label
List of currently supported formats and vertical alignments
Description
We support xx
style format labels grouped by 1d, 2d, and 3d.
Currently valid format labels cannot be added dynamically. Format functions
must be used for special cases.
Usage
list_valid_format_labels()
list_valid_aligns()
Value
-
list_valid_format_labels()
returns a nested list, with elements listing the supported 1d, 2d, and 3d format strings.
-
list_valid_aligns()
returns a character vector of valid vertical alignments.
Examples
list_valid_format_labels()
list_valid_aligns()
General title and footer accessors
Description
General title and footer accessors
Usage
main_title(obj)
## S4 method for signature 'MatrixPrintForm'
main_title(obj)
main_title(obj) <- value
## S4 replacement method for signature 'MatrixPrintForm'
main_title(obj) <- value
subtitles(obj)
## S4 method for signature 'MatrixPrintForm'
subtitles(obj)
subtitles(obj) <- value
## S4 replacement method for signature 'MatrixPrintForm'
subtitles(obj) <- value
page_titles(obj)
## S4 method for signature 'MatrixPrintForm'
page_titles(obj)
## S4 method for signature 'ANY'
page_titles(obj)
page_titles(obj) <- value
## S4 replacement method for signature 'MatrixPrintForm'
page_titles(obj) <- value
main_footer(obj)
## S4 method for signature 'MatrixPrintForm'
main_footer(obj)
main_footer(obj) <- value
## S4 replacement method for signature 'MatrixPrintForm'
main_footer(obj) <- value
prov_footer(obj)
## S4 method for signature 'MatrixPrintForm'
prov_footer(obj)
prov_footer(obj) <- value
## S4 replacement method for signature 'MatrixPrintForm'
prov_footer(obj) <- value
all_footers(obj)
all_titles(obj)
Arguments
obj |
( |
value |
character. New value. |
Value
A character scalar (main_title
), character vector (main_footer
), or
vector of length zero or more (subtitles
, page_titles
, prov_footer
) containing
the relevant title/footer contents.
Make row layout summary data frames for use during pagination
Description
All relevant information about table rows (e.g. indentations) is summarized in a data.frame
.
This function works only on rtables
and rlistings
objects, and not on their print
counterparts
(like MatrixPrintForm
).
Usage
make_row_df(
tt,
colwidths = NULL,
visible_only = TRUE,
rownum = 0,
indent = 0L,
path = character(),
incontent = FALSE,
repr_ext = 0L,
repr_inds = integer(),
sibpos = NA_integer_,
nsibs = NA_integer_,
max_width = NULL,
fontspec = font_spec(),
col_gap = 3L,
round_type = c("iec", "sas")
)
## S4 method for signature 'MatrixPrintForm'
make_row_df(
tt,
colwidths = NULL,
visible_only = TRUE,
rownum = 0,
indent = 0L,
path = character(),
incontent = FALSE,
repr_ext = 0L,
repr_inds = integer(),
sibpos = NA_integer_,
nsibs = NA_integer_,
max_width = NULL,
fontspec = font_spec(),
col_gap = mf_colgap(tt) %||% 3L,
round_type = c("iec", "sas")
)
Arguments
tt |
( |
colwidths |
( |
visible_only |
( |
rownum |
( |
indent |
( |
path |
( |
incontent |
( |
repr_ext |
( |
repr_inds |
( |
sibpos |
( |
nsibs |
( |
max_width |
( |
fontspec |
( |
col_gap |
( |
round_type |
( |
Details
When visible_only
is TRUE
(the default), methods should return a data.frame
with exactly one
row per visible row in the table-like object. This is useful when reasoning about how a table will
print, but does not reflect the full pathing space of the structure (though the paths which are given
will all work as is).
If supported, when visible_only
is FALSE
, every structural element of the table (in row-space)
will be reflected in the returned data.frame
, meaning the full pathing-space will be represented
but some rows in the layout summary will not represent printed rows in the table as it is displayed.
Most arguments beyond tt
and visible_only
are present so that make_row_df
methods can call
make_row_df
recursively and retain information, and should not be set during a top-level call.
Value
A data.frame
of row/column-structure information used by the pagination machinery.
Note
The technically present root tree node is excluded from the summary returned by
both make_row_df
and make_col_df
(see relevant functions inrtables
), as it is the
row/column structure of tt
and thus not useful for pathing or pagination.
Examples
# Expected error with matrix_form. For real case examples consult {rtables} documentation
mf <- basic_matrix_form(iris)
# make_row_df(mf) # Use table obj instead
Transform rtable
to a list of matrices which can be used for outputting
Description
Although rtable
s are represented as a tree data structure when outputting the table to ASCII or HTML,
it is useful to map the rtable
to an in-between state with the formatted cells in a matrix form.
Usage
matrix_form(
obj,
indent_rownames = FALSE,
expand_newlines = TRUE,
indent_size = 2,
fontspec = NULL,
col_gap = NULL,
round_type = c("iec", "sas")
)
## S4 method for signature 'MatrixPrintForm'
matrix_form(
obj,
indent_rownames = FALSE,
expand_newlines = TRUE,
indent_size = 2,
fontspec = NULL,
col_gap = NULL,
round_type = c("iec", "sas")
)
Arguments
obj |
( |
indent_rownames |
( |
expand_newlines |
( |
indent_size |
( |
fontspec |
( |
col_gap |
( |
round_type |
( |
Value
A MatrixPrintForm
classed list with an additional nrow_header
attribute indicating the
number of pseudo "rows" the column structure defines, with the following elements:
strings
The content, as it should be printed, of the top-left material, column headers, row labels, and cell values of
tt
.spans
The column-span information for each print-string in the strings matrix.
aligns
The text alignment for each print-string in the strings matrix.
display
Whether each print-string in the strings matrix should be printed or not.
row_info
The
data.frame
generated bybasic_pagdf()
.
Getters and setters for aspects of MatrixPrintForm
objects
Description
Most of these functions, particularly the setters, are intended almost exclusively for
internal use in, e.g., matrix_form
methods, and should generally not be called by end users.
Usage
mf_strings(mf)
mf_spans(mf)
mf_aligns(mf)
mf_display(mf)
mf_formats(mf)
mf_rinfo(mf)
mf_cinfo(mf)
mf_has_topleft(mf)
mf_lgrouping(mf)
mf_rfnotes(mf)
mf_nlheader(mf)
mf_nrheader(mf)
mf_colgap(mf)
mf_fontspec(mf)
mf_fontspec(mf) <- value
mf_strings(mf) <- value
mf_spans(mf) <- value
mf_aligns(mf) <- value
mf_display(mf) <- value
mf_formats(mf) <- value
mf_rinfo(mf) <- value
mf_cinfo(mf) <- value
mf_lgrouping(mf) <- value
mf_rfnotes(mf) <- value
mf_nrheader(mf) <- value
mf_colgap(mf) <- value
mf_ncol(mf)
mf_nrow(mf)
mf_ncol(mf) <- value
## S4 method for signature 'MatrixPrintForm'
ncol(x)
mpf_has_rlabels(mf)
mf_has_rlabels(mf)
Arguments
mf |
( |
value |
( |
x |
|
Value
Getters return the associated element of
mf
.Setters return the modified
mf
object.
Transform MatrixPrintForm
to RTF
Description
Experimental export to rich text format (RTF) via the r2rtf
package.
Usage
mpf_to_rtf(
mpf,
colwidths = NULL,
page_type = "letter",
pg_width = page_dim(page_type)[if (landscape) 2 else 1],
pg_height = page_dim(page_type)[if (landscape) 1 else 2],
landscape = FALSE,
margins = c(4, 4, 4, 4),
font_family = "Courier",
font_size = 8,
lineheight = 1,
fontspec = font_spec(font_family, font_size, lineheight),
round_type = round_type,
...
)
Arguments
mpf |
( |
colwidths |
( |
page_type |
( |
pg_width |
( |
pg_height |
( |
landscape |
( |
margins |
( |
font_family |
( |
font_size |
( |
lineheight |
( |
fontspec |
( |
round_type |
( |
... |
additional parameters passed to individual methods. |
Details
This function provides a low-level coercion of a MatrixPrintForm
object into
text containing the corresponding table in RTF. Currently, no pagination is done
at this level, and should be done prior to calling this function, though that
may change in the future.
Value
An RTF object.
Calculate font-specific string width
Description
This function returns the width of each element x
as a multiple of the width of the space character
for in declared font, rounded up to the nearest
integer. This is used extensively in the text rendering
(toString()
) and pagination machinery for
calculating word wrapping, default column widths,
lines per page, etc.
Usage
nchar_ttype(
x,
fontspec = font_spec(),
tol = sqrt(.Machine$double.eps),
raw = FALSE
)
Arguments
x |
( |
fontspec |
( |
tol |
( |
raw |
( |
Details
String width is defined in terms of spaces within
the specified font. For monospace fonts, this definition
collapses to the number of characters in the string
(nchar()
), but for truetype fonts it does not.
For raw = FALSE
, non-integer values (the norm in a truetype
setting) for the number of spaces a string takes up is rounded
up, unless the multiple is less than tol
above the last integer
before it. E.g., if k - num_spaces < tol
for an integer
k
, k
is returned instead of k+1
.
See Also
Examples
nchar_ttype("hi there!")
nchar_ttype("hi there!", font_spec("Times"))
Number of lines required to print a value
Description
Number of lines required to print a value
Usage
nlines(x, colwidths = NULL, max_width = NULL, fontspec, col_gap = NULL)
## S4 method for signature 'list'
nlines(x, colwidths = NULL, max_width = NULL, fontspec, col_gap = NULL)
## S4 method for signature 'NULL'
nlines(x, colwidths = NULL, max_width = NULL, fontspec, col_gap = NULL)
## S4 method for signature 'character'
nlines(x, colwidths = NULL, max_width = NULL, fontspec, col_gap = NULL)
Arguments
x |
( |
colwidths |
( |
max_width |
( |
fontspec |
( |
col_gap |
( |
Value
The number of lines needed to render the object x
.
Number of repeated columns
Description
When called on a table-like object using the formatters framework, this method returns the number of columns which are mandatorily repeated after each horizontal pagination.
Usage
num_rep_cols(obj)
## S4 method for signature 'ANY'
num_rep_cols(obj)
## S4 method for signature 'MatrixPrintForm'
num_rep_cols(obj)
num_rep_cols(obj) <- value
## S4 replacement method for signature 'ANY'
num_rep_cols(obj) <- value
## S4 replacement method for signature 'MatrixPrintForm'
num_rep_cols(obj) <- value
Arguments
obj |
( |
value |
( |
Details
Absent a class-specific method, this function returns 0, indicating no always-repeated columns.
Value
An integer.
Note
This number does not include row labels, the repetition of which is handled separately.
Examples
mpf <- basic_matrix_form(mtcars)
num_rep_cols(mpf)
lmpf <- basic_listing_mf(mtcars)
num_rep_cols(lmpf)
Activate font state
Description
Activate font state
Usage
open_font_dev(fontspec, silent = FALSE)
close_font_dev()
debug_font_dev()
undebug_font_dev()
Arguments
fontspec |
( |
silent |
( |
Details
The font device state is an environment with four variables guaranteed to be set:
open
(
logical(1)
)
whether a device is already open with font infofontspec
(
font_spec
)
the font specification, if any, that is currently active (list()
if none is).spacewidth
(
numeric(1)
)
the width of the space character in the currently active font.ismonospace
(
logical(1)
)
whether the specified font is monospaced.
open_font_dev
opens a pdf device with the specified font
only if there is not one currently open with the same font.
If a new device is opened, it caches spacewidth
and
ismonospace
for use in nchar_ttype
).
close_font_dev
closes any open font state device
and clears the cached values.
debug_font_dev
and undebug_font_dev
activate and deactivate, respectively,
logging of where in the call stack font devices are being opened.
Value
-
open_font_dev
returns a logical value indicating whether a new pdf device was opened. -
close_font_dev
,debug_font_dev
andundebug_font_dev
returnNULL
.
In all cases the value is returned invisibly.
Examples
open_font_dev(font_spec("Times"))
nchar_ttype("Hiya there", font_spec("Times"))
close_font_dev()
Pad a string and align within string
Description
Pad a string and align within string
Usage
padstr(x, n, just = list_valid_aligns(), fontspec = font_spec())
Arguments
x |
( |
n |
( |
just |
( |
fontspec |
( |
Value
x
, padded to be a string of length n
.
Examples
padstr("abc", 3)
padstr("abc", 4)
padstr("abc", 5)
padstr("abc", 5, "left")
padstr("abc", 5, "right")
## Not run:
# Expect error: "abc" has more than 1 characters
padstr("abc", 1)
## End(Not run)
Find pagination indices from pagination info data frame
Description
Pagination methods should typically call the make_row_df
method
for their object and then call this function on the resulting
pagination info data.frame
.
Usage
pag_indices_inner(
pagdf,
rlpp,
lpp_or_cpp = NA_integer_,
context_lpp_or_cpp = NA_integer_,
min_siblings,
nosplitin = character(),
verbose = FALSE,
row = TRUE,
have_col_fnotes = FALSE,
div_height = 1L,
col_gap = 3L,
has_rowlabels
)
Arguments
pagdf |
( |
rlpp |
( |
lpp_or_cpp |
( |
context_lpp_or_cpp |
( |
min_siblings |
( |
nosplitin |
( |
verbose |
( |
row |
( |
have_col_fnotes |
( |
div_height |
( |
col_gap |
( |
has_rowlabels |
( |
Details
pab_indices_inner
implements the core pagination algorithm (see below)
for a single direction (vertical if row = TRUE
(the default), horizontal otherwise)
based on the pagination data frame and (already adjusted for non-body rows/columns)
lines (or characters) per page.
Value
A list
containing a vector of row numbers, broken up by page.
Pagination Algorithm
Pagination is performed independently in the vertical and horizontal directions based solely on a pagination data frame, which includes the following information for each row/column:
Number of lines/characters rendering the row will take after word-wrapping (
self_extent
)The indices (
reprint_inds
) and number of lines (par_extent
) of the rows which act as context for the rowThe row's number of siblings and position within its siblings
Given lpp
(cpp
) is already adjusted for rendered elements which
are not rows/columns and a data frame of pagination information,
pagination is performed via the following algorithm with start = 1
.
Core Pagination Algorithm:
Initial guess for pagination position is
start + lpp
(start + cpp
)While the guess is not a valid pagination position, and
guess > start
, decrement guess and repeat.An error is thrown if all possible pagination positions between
start
andstart + lpp
(start + cpp
) would be< start
after decrementing
Retain pagination index
If pagination point was less than
NROW(tt)
(ncol(tt)
), setstart
topos + 1
, and repeat steps (1) - (4).
Validating Pagination Position:
Given an (already adjusted) lpp
or cpp
value, a pagination is invalid if:
The rows/columns on the page would take more than (adjusted)
lpp
lines/cpp
characters to render including:word-wrapping
(vertical only) context repetition
(vertical only) footnote messages and/or section divider lines take up too many lines after rendering rows
(vertical only) row is a label or content (row-group summary) row
(vertical only) row at the pagination point has siblings, and it has less than
min_siblings
preceding or following siblingspagination would occur within a sub-table listed in
nosplitin
Examples
mypgdf <- basic_pagdf(row.names(mtcars))
paginds <- pag_indices_inner(mypgdf, rlpp = 15, min_siblings = 0)
lapply(paginds, function(x) mtcars[x, ])
Create a row of a pagination data frame
Description
Create a row of a pagination data frame
Usage
pagdfrow(
row,
nm = obj_name(row),
lab = obj_label(row),
rnum,
pth,
sibpos = NA_integer_,
nsibs = NA_integer_,
extent = nlines(row, colwidths, fontspec = fontspec),
colwidths = NULL,
repext = 0L,
repind = integer(),
indent = 0L,
rclass = class(row),
nrowrefs = 0L,
ncellrefs = 0L,
nreflines = 0L,
force_page = FALSE,
page_title = NA_character_,
trailing_sep = NA_character_,
fontspec
)
Arguments
row |
( |
nm |
( |
lab |
( |
rnum |
( |
pth |
( |
sibpos |
( |
nsibs |
( |
extent |
( |
colwidths |
( |
repext |
( |
repind |
( |
indent |
( |
rclass |
( |
nrowrefs |
( |
ncellrefs |
( |
nreflines |
( |
force_page |
( |
page_title |
( |
trailing_sep |
( |
fontspec |
( |
Value
A single row data.frame
with the appropriate columns for a pagination info data frame.
Determine lines per page (LPP) and characters per page (CPP) based on font and page type
Description
Determine lines per page (LPP) and characters per page (CPP) based on font and page type
Usage
page_lcpp(
page_type = page_types(),
landscape = FALSE,
font_family = "Courier",
font_size = 8,
lineheight = 1,
margins = c(top = 0.5, bottom = 0.5, left = 0.75, right = 0.75),
pg_width = NULL,
pg_height = NULL,
fontspec = font_spec(font_family, font_size, lineheight)
)
Arguments
page_type |
( |
landscape |
( |
font_family |
( |
font_size |
( |
lineheight |
( |
margins |
( |
pg_width |
( |
pg_height |
( |
fontspec |
( |
Value
A named list containing LPP (lines per page) and CPP (characters per page) elements suitable for use by the pagination machinery.
Examples
page_lcpp()
page_lcpp(font_size = 10)
page_lcpp("a4", font_size = 10)
page_lcpp(margins = c(top = 1, bottom = 1, left = 1, right = 1))
page_lcpp(pg_width = 10, pg_height = 15)
Supported named page types
Description
List supported named page types.
Usage
page_types()
page_dim(page_type)
Arguments
page_type |
( |
Value
-
page_types
returns a character vector of supported page types -
page_dim
returns the dimensions (width, then height) of the selected page type.
Examples
page_types()
page_dim("a4")
Paginate a table-like object for rendering
Description
These functions perform or diagnose bi-directional pagination on an object.
Usage
paginate_indices(
obj,
page_type = "letter",
font_family = "Courier",
font_size = 8,
lineheight = 1,
landscape = FALSE,
pg_width = NULL,
pg_height = NULL,
margins = c(top = 0.5, bottom = 0.5, left = 0.75, right = 0.75),
lpp = NA_integer_,
cpp = NA_integer_,
min_siblings = 2,
nosplitin = list(rows = character(), cols = character()),
colwidths = NULL,
tf_wrap = FALSE,
max_width = NULL,
indent_size = 2,
pg_size_spec = NULL,
rep_cols = num_rep_cols(obj),
col_gap = 3,
fontspec = font_spec(font_family, font_size, lineheight),
round_type = c("iec", "sas"),
verbose = FALSE
)
paginate_to_mpfs(
obj,
page_type = "letter",
font_family = "Courier",
font_size = 8,
lineheight = 1,
landscape = FALSE,
pg_width = NULL,
pg_height = NULL,
margins = c(top = 0.5, bottom = 0.5, left = 0.75, right = 0.75),
lpp = NA_integer_,
cpp = NA_integer_,
min_siblings = 2,
nosplitin = character(),
colwidths = NULL,
tf_wrap = FALSE,
max_width = NULL,
indent_size = 2,
pg_size_spec = NULL,
page_num = default_page_number(),
rep_cols = NULL,
col_gap = 3,
fontspec = font_spec(font_family, font_size, lineheight),
round_type = c("iec", "sas"),
verbose = FALSE
)
diagnose_pagination(
obj,
page_type = "letter",
font_family = "Courier",
font_size = 8,
lineheight = 1,
landscape = FALSE,
pg_width = NULL,
pg_height = NULL,
margins = c(top = 0.5, bottom = 0.5, left = 0.75, right = 0.75),
lpp = NA_integer_,
cpp = NA_integer_,
min_siblings = 2,
nosplitin = character(),
colwidths = propose_column_widths(matrix_form(obj, TRUE, round_type = round_type),
fontspec = fontspec, round_type = round_type),
tf_wrap = FALSE,
max_width = NULL,
indent_size = 2,
pg_size_spec = NULL,
rep_cols = num_rep_cols(obj),
col_gap = 3,
verbose = FALSE,
fontspec = font_spec(font_family, font_size, lineheight),
round_type = c("iec", "sas"),
...
)
Arguments
obj |
( |
page_type |
( |
font_family |
( |
font_size |
( |
lineheight |
( |
landscape |
( |
pg_width |
( |
pg_height |
( |
margins |
( |
lpp |
( |
cpp |
( |
min_siblings |
( |
nosplitin |
( |
colwidths |
( |
tf_wrap |
( |
max_width |
( |
indent_size |
( |
pg_size_spec |
( |
rep_cols |
( |
col_gap |
( |
fontspec |
( |
round_type |
( |
verbose |
( |
page_num |
( |
... |
additional parameters passed to individual methods. |
Details
paginate_indices
renders obj
into a MatrixPrintForm
(MPF), then uses that representation to
calculate the rows and columns of obj
corresponding to each page of the pagination of obj
, but
simply returns these indices rather than paginating obj
itself (see Details for an important caveat).
paginate_to_mpfs
renders obj
into its MPF intermediate representation, then paginates that MPF into
component MPFs each corresponding to an individual page and returns those in a list
.
diagnose_pagination
attempts pagination via paginate_to_mpfs
, then returns diagnostic information
which explains why page breaks were positioned where they were, or alternatively why no valid pagination
could be found.
All three of these functions generally support all classes which have a corresponding matrix_form()
method which returns a valid MatrixPrintForm
object (including MatrixPrintForm
objects themselves).
paginate_indices
is directly called by paginate_to_mpfs
(and thus diagnose_pagination
). For most
classes, and most tables represented by supported classes, calling paginate_to_mpfs
is equivalent to a
manual paginate_indices -> subset obj into pages -> matrix_form
workflow.
The exception to this equivalence is objects which support "forced pagination", or pagination logic which
is built into the object itself rather than being a function of space on a page. Forced pagination
generally involves the creation of, e.g., page-specific titles which apply to these forced paginations.
paginate_to_mpfs
and diagnose_pagination
support forced pagination by automatically calling the
do_forced_paginate()
generic on the object and then paginating each object returned by that generic
separately. The assumption here, then, is that page-specific titles and such are handled by the class'
do_forced_paginate()
method.
paginate_indices
, on the other hand, does not support forced pagination, because it returns only a
set of indices for row and column subsetting for each page, and thus cannot retain any changes, e.g.,
to titles, done within do_forced_paginate()
. paginate_indices
does call do_forced_paginate()
, but
instead of continuing it throws an error in the case that the result is larger than a single "page".
diagnose_pagination
attempts pagination and then, regardless of success or failure, returns diagnostic
information about pagination attempts (if any) after each row and column.
The diagnostics data reflects the final time the pagination algorithm evaluated a page break at the specified location, regardless of how many times the position was assessed in total.
To get information about intermediate attempts, perform pagination with verbose = TRUE
and inspect
the messages in order.
Value
-
paginate_indices
returns alist
with two elements of the same length:pag_row_indices
andpag_col_indices
. -
paginate_to_mpfs
returns alist
ofMatrixPrintForm
objects representing each individual page after pagination (including forced pagination if necessary).
-
diagnose_pagination
returns alist
containing:lpp_diagnostics
Diagnostic information regarding lines per page.
row_diagnostics
Basic information about rows, whether pagination was attempted after each row, and the final result of such an attempt, if made.
cpp_diagnostics
Diagnostic information regarding columns per page.
col_diagnostics
Very basic information about leaf columns, whether pagination was attempted after each leaf column, ad the final result of such attempts, if made.
Note
For diagnose_pagination
, the column labels are not displayed in the col_diagnostics
element
due to certain internal implementation details; rather the diagnostics are reported in terms of
absolute (leaf) column position. This is a known limitation, and may eventually be changed, but the
information remains useful as it is currently reported.
diagnose_pagination
is intended for interactive debugging use and should not be programmed against,
as the exact content and form of the verbose messages it captures and returns is subject to change.
Because diagnose_pagination
relies on capture.output(type = "message")
, it cannot be used within the
testthat
(and likely other) testing frameworks, and likely cannot be used within knitr
/rmarkdown
contexts either, as this clashes with those systems' capture of messages.
Examples
mpf <- basic_matrix_form(mtcars)
paginate_indices(mpf, pg_width = 5, pg_height = 3)
paginate_to_mpfs(mpf, pg_width = 5, pg_height = 3)
diagnose_pagination(mpf, pg_width = 5, pg_height = 3)
clws <- propose_column_widths(mpf)
clws[1] <- floor(clws[1] / 3)
dgnost <- diagnose_pagination(mpf, pg_width = 5, pg_height = 3, colwidths = clws)
try(diagnose_pagination(mpf, pg_width = 1)) # fails
Pagination
Description
Pagination
Pagination Algorithm
Pagination is performed independently in the vertical and horizontal directions based solely on a pagination data frame, which includes the following information for each row/column:
Number of lines/characters rendering the row will take after word-wrapping (
self_extent
)The indices (
reprint_inds
) and number of lines (par_extent
) of the rows which act as context for the rowThe row's number of siblings and position within its siblings
Given lpp
(cpp
) is already adjusted for rendered elements which
are not rows/columns and a data frame of pagination information,
pagination is performed via the following algorithm with start = 1
.
Core Pagination Algorithm:
Initial guess for pagination position is
start + lpp
(start + cpp
)While the guess is not a valid pagination position, and
guess > start
, decrement guess and repeat.An error is thrown if all possible pagination positions between
start
andstart + lpp
(start + cpp
) would be< start
after decrementing
Retain pagination index
If pagination point was less than
NROW(tt)
(ncol(tt)
), setstart
topos + 1
, and repeat steps (1) - (4).
Validating Pagination Position:
Given an (already adjusted) lpp
or cpp
value, a pagination is invalid if:
The rows/columns on the page would take more than (adjusted)
lpp
lines/cpp
characters to render including:word-wrapping
(vertical only) context repetition
(vertical only) footnote messages and/or section divider lines take up too many lines after rendering rows
(vertical only) row is a label or content (row-group summary) row
(vertical only) row at the pagination point has siblings, and it has less than
min_siblings
preceding or following siblingspagination would occur within a sub-table listed in
nosplitin
Description
Print an R object. See print()
.
Usage
## S4 method for signature 'ANY'
print(x, ...)
Arguments
x |
an object used to select a method. |
... |
further arguments passed to or from other methods. |
Propose column widths based on the MatrixPrintForm
of an object
Description
Row names are also considered a column for the output.
Usage
propose_column_widths(
x,
indent_size = 2,
fontspec = font_spec(),
round_type = c("iec", "sas")
)
Arguments
x |
( |
indent_size |
( |
fontspec |
( |
round_type |
( |
Value
A vector of column widths based on the content of x
for use in printing and pagination.
Examples
mf <- basic_matrix_form(mtcars)
propose_column_widths(mf)
Create a row for a referential footnote information data frame
Description
Create a row for a referential footnote information data frame
Usage
ref_df_row(
row_path = NA_character_,
col_path = NA_character_,
row = NA_integer_,
col = NA_integer_,
symbol = NA_character_,
ref_index = NA_integer_,
msg = NA_character_,
max_width = NULL
)
Arguments
row_path |
( |
col_path |
( |
row |
( |
col |
( |
symbol |
( |
ref_index |
( |
msg |
( |
max_width |
( |
Value
A single row data frame with the appropriate columns.
Round and prepare a value for display
Description
This function is used within format_value()
to prepare numeric values within
cells for formatting and display.
Usage
round_fmt(x, digits, na_str = "NA", round_type = c("iec", "sas"))
Arguments
x |
( |
digits |
( |
na_str |
( |
round_type |
( |
Details
This function combines rounding behavior with the strict decimal display of
sprintf()
. By default, R's standards-compliant round()
function (see the Details section of that documentation) is used. The exact
behavior is as follows:
If
x
isNA
, the value ofna_str
is returned.If
x
is non-NA
butdigits
isNA
,x
is converted to a character and returned.If
x
anddigits
are both non-NA,round()
is called first, and thensprintf()
is used to convert the rounded value to a character with the appropriate number of trailing zeros enforced.
Value
A character value representing the value after rounding, containing any trailing zeros
required to display exactly digits
elements.
Note
This differs from the base R round()
function in that NA
digits indicate x
should be converted
to character and returned unchanged whereas round(x, digits=NA)
returns NA
for all values of x
.
This behavior will differ from as.character(round(x, digits = digits))
in the case where there are
not at least digits
significant digits after the decimal that remain after rounding. It may differ from
sprintf("\%.Nf", x)
for values ending in 5
after the decimal place on many popular operating systems
due to round
's stricter adherence to the IEC 60559 standard, particularly for R versions > 4.0.0 (see
warning in round()
documentation).
See Also
format_value()
, round()
, sprintf()
Examples
round_fmt(0, digits = 3)
round_fmt(.395, digits = 2)
round_fmt(NA, digits = 1)
round_fmt(NA, digits = 1, na_str = "-")
round_fmt(2.765923, digits = NA)
round_fmt(0.845, digits = 2)
round_fmt(0.845, digits = 2, round_type = "sas")
Transform a vector of spans (with duplication) into a visibility vector
Description
Transform a vector of spans (with duplication) into a visibility vector
Usage
spans_to_viscell(spans)
Arguments
spans |
( |
Details
The values of spans
are assumed to be repeated such that each individual position covered by the
span has the repeated value.
This means that each block of values in spans
must be of a length at least equal to its value
(i.e. two 2s, three 3s, etc).
This function correctly handles cases where two spans of the same size are next to each other; i.e., a block of four 2s represents two large cells each of which spans two individual cells.
Value
A logical vector the same length as spans
indicating whether the contents of a string vector
with those spans is valid.
Note
Currently no checking or enforcement is done to verify that the vector of spans is valid according to the specifications described in the Details section above.
Examples
spans_to_viscell(c(2, 2, 2, 2, 1, 3, 3, 3))
wrap string given a Truetype font
Description
wrap string given a Truetype font
Usage
split_word_ttype(str, width, fontspec, min_ok_chars)
wrap_string_ttype(
str,
width,
fontspec,
collapse = NULL,
min_ok_chars = min(floor(nchar(str)/2), 4, floor(width/2)),
wordbreak_ok = TRUE
)
Arguments
str |
( |
width |
( |
fontspec |
( |
min_ok_chars |
( |
collapse |
( |
wordbreak_ok |
( |
Value
str
, broken up into a word-wrapped vector
Spread an integer to a given length
Description
Spread an integer to a given length
Usage
spread_integer(x, len)
Arguments
x |
( |
len |
( |
Value
If x
is a scalar whole number value (see is.wholenumber()
), the value x
is repeated len
times.
Otherwise, an error is thrown.
Examples
spread_integer(3, 1)
spread_integer(0, 3)
spread_integer(1, 3)
spread_integer(2, 3)
spread_integer(3, 3)
spread_integer(4, 3)
spread_integer(5, 3)
spread_integer(6, 3)
spread_integer(7, 3)
Specify text format via a sprintf
format string
Description
Specify text format via a sprintf
format string
Usage
sprintf_format(format)
Arguments
format |
( |
Value
A formatting function which wraps and applies the specified sprintf
-style format
to string format
.
See Also
Examples
fmtfun <- sprintf_format("(N=%i")
format_value(100, format = fmtfun)
fmtfun2 <- sprintf_format("%.4f - %.2f")
format_value(list(12.23456, 2.724))
Access or (recursively) set table inset
Description
Table inset is the amount of characters that the body of a table, referential footnotes, and main footer material are inset from the left-alignment of the titles and provenance footer materials.
Usage
table_inset(obj)
## S4 method for signature 'MatrixPrintForm'
table_inset(obj)
table_inset(obj) <- value
## S4 replacement method for signature 'MatrixPrintForm'
table_inset(obj) <- value
Arguments
obj |
( |
value |
( |
Value
-
table_inset
returns the integer value that the table body (including column heading information and section dividers), referential footnotes, and main footer should be inset from the left alignment of the titles and provenance footers during rendering. -
table_inset<-
returnsobj
with the new table_inset value applied recursively to it and all its subtables.
Create spoof matrix form from a data frame
Description
Useful functions for writing tests and examples, and a starting point for
more sophisticated custom matrix_form
methods.
Usage
basic_matrix_form(
df,
indent_rownames = FALSE,
parent_path = NULL,
ignore_rownames = FALSE,
add_decoration = FALSE,
fontspec = font_spec(),
split_labels = NULL,
data_labels = NULL,
num_rep_cols = 0L
)
basic_listing_mf(
df,
keycols = names(df)[1],
add_decoration = TRUE,
fontspec = font_spec()
)
Arguments
df |
( |
indent_rownames |
( |
parent_path |
( |
ignore_rownames |
( |
add_decoration |
( |
fontspec |
( |
split_labels |
( |
data_labels |
( |
num_rep_cols |
( |
keycols |
( |
Details
If some of the column has a obj_format assigned, it will be respected for all column
values except for label rows, if present (see parameter split_labels
).
Value
A valid MatrixPrintForm
object representing df
that is ready for
ASCII rendering.
A valid MatrixPrintForm
object representing df
as a listing that is ready for ASCII
rendering.
Functions
-
basic_listing_mf()
: Create aMatrixPrintForm
object from data framedf
that respects the default formats for a listing object.
Examples
mform <- basic_matrix_form(mtcars)
cat(toString(mform))
# Advanced test case with label rows
library(dplyr)
iris_output <- iris %>%
group_by(Species) %>%
summarize("all obs" = round(mean(Petal.Length), 2)) %>%
mutate("DataRow_label" = "Mean")
mf <- basic_matrix_form(iris_output,
indent_rownames = TRUE,
split_labels = "Species", data_labels = "DataRow_label"
)
cat(toString(mf))
mform <- basic_listing_mf(mtcars)
cat(toString(mform))
Transform objects into string representations
Description
Transform a complex object into a string representation ready to be printed or written to a plain-text file.
All objects that are printed to console pass via toString
. This function allows
fundamental formatting specifications to be applied to final output, like column widths
and relative wrapping (width
), title and footer wrapping (tf_wrap = TRUE
and
max_width
), and horizontal separator character (e.g. hsep = "+"
).
Usage
toString(x, ...)
## S4 method for signature 'MatrixPrintForm'
toString(
x,
widths = NULL,
tf_wrap = FALSE,
max_width = NULL,
col_gap = mf_colgap(x),
hsep = NULL,
fontspec = font_spec(),
ttype_ok = FALSE,
round_type = c("iec", "sas")
)
Arguments
x |
( |
... |
additional parameters passed to individual methods. |
widths |
( |
tf_wrap |
( |
max_width |
( |
col_gap |
( |
hsep |
( |
fontspec |
( |
ttype_ok |
( |
round_type |
( |
Details
Manual insertion of newlines is not supported when tf_wrap = TRUE
and will result in a warning and
undefined wrapping behavior. Passing vectors of already split strings remains supported, however in this
case each string is word-wrapped separately with the behavior described above.
Value
A character string containing the ASCII rendering of the table-like object represented by x
.
See Also
Examples
mform <- basic_matrix_form(mtcars)
cat(toString(mform))
Get label attributes of variables in a data.frame
Description
Variable labels can be stored as a label
attribute for each variable.
This functions returns a named character vector with the variable labels
(or empty strings if not specified).
Usage
var_labels(x, fill = FALSE)
Arguments
x |
( |
fill |
( |
Value
a named character vector of variable labels from x
, with names corresponding
to variable names.
Examples
x <- iris
var_labels(x)
var_labels(x) <- paste("label for", names(iris))
var_labels(x)
Set label attributes of all variables in a data.frame
Description
Variable labels can be stored as the label
attribute for each variable.
This functions sets all non-missing (non-NA
) variable labels in a data.frame
.
Usage
var_labels(x) <- value
Arguments
x |
( |
value |
( |
Value
x
with modified variable labels.
Examples
x <- iris
var_labels(x)
var_labels(x) <- paste("label for", names(iris))
var_labels(x)
if (interactive()) {
View(x) # in RStudio data viewer labels are displayed
}
Remove variable labels of a data.frame
Description
Remove label
attribute from all variables in a data frame.
Usage
var_labels_remove(x)
Arguments
x |
( |
Value
x
with its variable labels stripped.
Examples
x <- var_labels_remove(iris)
Copy and change variable labels of a data.frame
Description
Relabel a subset of the variables.
Usage
var_relabel(x, ...)
Arguments
x |
( |
... |
name-value pairs, where each name corresponds to a variable name in
|
Value
A copy of x
with labels modified according to ...
Examples
x <- var_relabel(iris, Sepal.Length = "Sepal Length of iris flower")
var_labels(x)
Find column indices for vertical pagination
Description
Find column indices for vertical pagination
Usage
vert_pag_indices(
obj,
cpp = 40,
colwidths = NULL,
verbose = FALSE,
rep_cols = 0L,
fontspec,
nosplitin = character(),
round_type = c("iec", "sas")
)
Arguments
obj |
( |
cpp |
( |
colwidths |
( |
verbose |
( |
rep_cols |
( |
fontspec |
( |
nosplitin |
( |
round_type |
( |
Value
A list
partitioning the vector of column indices into subsets for 1 or more horizontally paginated pages.
Examples
mf <- basic_matrix_form(df = mtcars)
colpaginds <- vert_pag_indices(mf, fontspec = font_spec())
lapply(colpaginds, function(j) mtcars[, j, drop = FALSE])
Return an object with a label attribute
Description
Return an object with a label attribute
Usage
with_label(x, label)
Arguments
x |
( |
label |
( |
Value
x
labeled by label
. Note that the exact mechanism of labeling should be considered
an internal implementation detail, but the label can always be retrieved via obj_label
.
Examples
x <- with_label(c(1, 2, 3), label = "Test")
obj_label(x)
Wrap a string to a precise width
Description
Core wrapping functionality that preserves whitespace. Newline character "\n"
is not supported
by core functionality stringi::stri_wrap()
. This is usually solved beforehand by matrix_form()
.
If the width is smaller than any large word, these will be truncated after width
characters. If
the split leaves trailing groups of empty spaces, they will be dropped.
Usage
wrap_string(str, width, collapse = NULL, fontspec = font_spec())
wrap_txt(str, width, collapse = NULL, fontspec = font_spec())
Arguments
str |
( |
width |
( |
collapse |
( |
fontspec |
( |
Details
Word wrapping happens similarly to stringi::stri_wrap()
with the following difference: individual
words which are longer than max_width
are broken up in a way that fits with other word wrapping.
Value
A string if str
is one element and if collapse = NULL
. Otherwise, a list of elements
(if length(str) > 1
) that can contain strings or vectors of characters (if collapse = NULL
).
Functions
-
wrap_txt()
: Deprecated function. Please usewrap_string()
instead.
Examples
str <- list(
" , something really \\tnot very good", # \t needs to be escaped
" but I keep it12 "
)
wrap_string(str, 5, collapse = "\n")
wrap_txt(str, 5, collapse = NULL)