Title: | ASCII Formatting for Values and Tables |
---|---|
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. |
Authors: | Gabriel Becker [aut] (original creator of the package), Adrian Waddell [aut], Davide Garolini [ctb], Emily de la Rua [ctb], Abinaya Yogasekaram [ctb], Joe Zhu [ctb, cre], F. Hoffmann-La Roche AG [cph, fnd] |
Maintainer: | Joe Zhu <[email protected]> |
License: | Apache License 2.0 |
Version: | 0.5.9.9003 |
Built: | 2024-10-28 09:22:26 UTC |
Source: | https://github.com/insightsengineering/formatters |
Returns a minimal pagination info data.frame
(with no info on siblings, footnotes, etc.).
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() )
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() )
rnames |
( |
labs |
( |
rnums |
( |
extents |
( |
rclass |
( |
parent_path |
( |
paths |
( |
fontspec |
( |
A data.frame
suitable for use in both the MatrixPrintForm
constructor and the pagination machinery.
basic_pagdf(c("hi", "there"))
basic_pagdf(c("hi", "there"))
Utility functions for checking formats and alignments.
is_valid_format(x, stop_otherwise = FALSE) check_aligns(algn)
is_valid_format(x, stop_otherwise = FALSE) check_aligns(algn)
x |
( |
stop_otherwise |
( |
algn |
( |
is_valid_format
returns TRUE
if x
is NULL
, a supported format string, or a function, and
FALSE
otherwise.
check_aligns
returns TRUE
if the provided alignments are supported, otherwise, an error is thrown.
If x
is a function, no check is performed to verify that it returns a valid format.
is_valid_format("xx.x") is_valid_format("fakeyfake") check_aligns(c("decimal", "dec_right"))
is_valid_format("xx.x") is_valid_format("fakeyfake") check_aligns(c("decimal", "dec_right"))
Aligning decimal values of string matrix. Allowed alignments are: dec_left
, dec_right
,
and decimal
.
decimal_align(string_mat, align_mat)
decimal_align(string_mat, align_mat)
string_mat |
( |
align_mat |
( |
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.
A processed string matrix of class MatrixPrintForm
with decimal-aligned values.
dfmf <- basic_matrix_form(mtcars[1:5, ]) aligns <- mf_aligns(dfmf) aligns[, -c(1)] <- "dec_left" decimal_align(mf_strings(dfmf), aligns)
dfmf <- basic_matrix_form(mtcars[1:5, ]) aligns <- mf_aligns(dfmf) aligns[, -c(1)] <- "dec_left" decimal_align(mf_strings(dfmf), aligns)
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.
default_hsep() set_default_hsep(hsep_char) default_hsep() set_default_hsep(hsep_char)
default_hsep() set_default_hsep(hsep_char) default_hsep() set_default_hsep(hsep_char)
hsep_char |
( |
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.
default_hsep() set_default_hsep("o") default_hsep() default_hsep() set_default_hsep("o") default_hsep()
default_hsep() set_default_hsep("o") default_hsep() default_hsep() set_default_hsep("o") default_hsep()
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.
default_page_number() set_default_page_number(page_number)
default_page_number() set_default_page_number(page_number)
page_number |
( |
The page number format string (NULL
if not set).
default_page_number() set_default_page_number("page {i} of {n}") default_page_number()
default_page_number() set_default_page_number("page {i} of {n}") default_page_number()
Divider height
divider_height(obj) ## S4 method for signature 'ANY' divider_height(obj)
divider_height(obj) ## S4 method for signature 'ANY' divider_height(obj)
obj |
( |
The height, in lines of text, of the divider between header and body. Currently
returns 1L
for the default method.
divider_height(mtcars)
divider_height(mtcars)
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.
do_forced_paginate(obj) ## S4 method for signature 'ANY' do_forced_paginate(obj)
do_forced_paginate(obj) ## S4 method for signature 'ANY' do_forced_paginate(obj)
obj |
( |
A list of sub-objects, which will be further paginated by the standard pagination algorithm.
Simulated CDISC-like data for examples
ex_adsl ex_adae ex_adaette ex_adtte ex_adcm ex_adlb ex_admh ex_adqs ex_adrs ex_advs
ex_adsl ex_adae ex_adaette ex_adtte ex_adcm ex_adlb ex_admh ex_adqs ex_adrs ex_advs
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.
The PDF output from this function is based on the ASCII output created with toString()
.
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 )
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 )
x |
( |
file |
( |
page_type |
( |
landscape |
( |
pg_width |
( |
pg_height |
( |
width |
Please use the |
height |
Please use the |
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 |
( |
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
.
## 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)
## 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)
Experimental export to the rich text format (RTF) format.
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), ... )
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), ... )
x |
( |
file |
( |
colwidths |
( |
page_type |
( |
pg_width |
( |
pg_height |
( |
landscape |
( |
margins |
( |
font_family |
( |
font_size |
( |
lineheight |
( |
fontspec |
( |
... |
additional parameters passed to |
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()
.
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
.
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 )
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 )
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 |
( |
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.
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.
export_as_txt(basic_matrix_form(mtcars), pg_height = 5, pg_width = 4)
export_as_txt(basic_matrix_form(mtcars), pg_height = 5, pg_width = 4)
Format configuration
fmt_config(format = NULL, na_str = "NA", align = "center")
fmt_config(format = NULL, na_str = "NA", align = "center")
format |
( |
na_str |
( |
align |
( |
An object of class fmt_config
which contains the following elements:
format
na_str
align
fmt_config(format = "xx.xx", na_str = "-", align = "left") fmt_config(format = "xx.xx - xx.xx", align = "right")
fmt_config(format = "xx.xx", na_str = "-", align = "left") fmt_config(format = "xx.xx - xx.xx", align = "right")
Font size specification
font_spec(font_family = "Courier", font_size = 8, lineheight = 1)
font_spec(font_family = "Courier", font_size = 8, lineheight = 1)
font_family |
( |
font_size |
( |
lineheight |
( |
Passing the output of this constructor to the rendering or pagination machinery defines a font for use when calculating word wrapping and pagination.
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.
nchar_ttype()
, toString()
, pagination_algo
, export_as_pdf()
fspec <- font_spec("Courier", 8, 1) lets <- paste(letters, collapse = "") nchar_ttype(lets, fspec) fspec2 <- font_spec("Times", 8, 1) nchar_ttype(lets, fspec2)
fspec <- font_spec("Courier", 8, 1) lets <- paste(letters, collapse = "") nchar_ttype(lets, fspec) fspec2 <- font_spec("Times", 8, 1) nchar_ttype(lets, fspec2)
format
informationConverts a (possibly compound) value into a string using the format
information
format_value(x, format = NULL, output = c("ascii", "html"), na_str = "NA")
format_value(x, format = NULL, output = c("ascii", "html"), na_str = "NA")
x |
( |
format |
( |
output |
( |
na_str |
( |
A length-zero value for na_str
will be interpreted as "NA"
.
Formatted text representing the cell x
.
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>"))
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%||%
(if length-0) alternative operator
a %||% b
a %||% b
a |
( |
b |
( |
a
if it is not of length 0, otherwise b
.
6 %||% 10 character() %||% "hi" NULL %||% "hi"
6 %||% 10 character() %||% "hi" NULL %||% "hi"
Check if a value is a whole number
is.wholenumber(x, tol = .Machine$double.eps^0.5)
is.wholenumber(x, tol = .Machine$double.eps^0.5)
x |
( |
tol |
( |
TRUE
if x
is within tol
of zero, FALSE
otherwise.
is.wholenumber(5) is.wholenumber(5.00000000000000001) is.wholenumber(.5)
is.wholenumber(5) is.wholenumber(5.00000000000000001) is.wholenumber(.5)
Getters and setters for basic, relatively universal attributes of "table-like" objects.
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
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
obj |
( |
value |
character(1). The new label |
The name, format, or label of obj
for getters, or obj
after modification for setters.
with_label
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.
list_valid_format_labels() list_valid_aligns()
list_valid_format_labels() list_valid_aligns()
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.
list_valid_format_labels() list_valid_aligns()
list_valid_format_labels() list_valid_aligns()
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
).
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 ) ## 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 )
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 ) ## 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 )
tt |
( |
colwidths |
( |
visible_only |
( |
rownum |
( |
indent |
( |
path |
( |
incontent |
( |
repr_ext |
( |
repr_inds |
( |
sibpos |
( |
nsibs |
( |
max_width |
( |
fontspec |
( |
col_gap |
( |
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.
A data.frame
of row/column-structure information used by the pagination machinery.
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.
# 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
# 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
rtable
to a list of matrices which can be used for outputtingAlthough 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.
matrix_form( obj, indent_rownames = FALSE, expand_newlines = TRUE, indent_size = 2, fontspec = NULL, col_gap = NULL ) ## S4 method for signature 'MatrixPrintForm' matrix_form( obj, indent_rownames = FALSE, expand_newlines = TRUE, indent_size = 2, fontspec = NULL, col_gap = NULL )
matrix_form( obj, indent_rownames = FALSE, expand_newlines = TRUE, indent_size = 2, fontspec = NULL, col_gap = NULL ) ## S4 method for signature 'MatrixPrintForm' matrix_form( obj, indent_rownames = FALSE, expand_newlines = TRUE, indent_size = 2, fontspec = NULL, col_gap = NULL )
obj |
( |
indent_rownames |
( |
expand_newlines |
( |
indent_size |
( |
fontspec |
( |
col_gap |
( |
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 by basic_pagdf()
.
Constructor for MatrixPrintForm
, an intermediate representation for ASCII table printing.
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 )
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 )
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 |
( |
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
in strings
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
The bare constructor for the MatrixPrintForm
should generally
only be called by matrix_form
custom methods, and almost never from other code.
basic_matrix_form(iris) # calls matrix_form which calls this constructor
basic_matrix_form(iris) # calls matrix_form which calls this constructor
The MatrixPrintForm
class, an intermediate representation for ASCII table printing.
MatrixPrintForm
objectsMost 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.
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)
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)
mf |
( |
value |
( |
x |
|
Getters return the associated element of mf
.
Setters return the modified mf
object.
MatrixPrintForm
to RTFExperimental export to rich text format (RTF) via the r2rtf
package.
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), ... )
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), ... )
mpf |
( |
colwidths |
( |
page_type |
( |
pg_width |
( |
pg_height |
( |
landscape |
( |
margins |
( |
font_family |
( |
font_size |
( |
lineheight |
( |
fontspec |
( |
... |
additional parameters passed to individual methods. |
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.
An RTF object.
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.
nchar_ttype( x, fontspec = font_spec(), tol = sqrt(.Machine$double.eps), raw = FALSE )
nchar_ttype( x, fontspec = font_spec(), tol = sqrt(.Machine$double.eps), raw = FALSE )
x |
( |
fontspec |
( |
tol |
( |
raw |
( |
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
.
nchar_ttype("hi there!") nchar_ttype("hi there!", font_spec("Times"))
nchar_ttype("hi there!") nchar_ttype("hi there!", font_spec("Times"))
Number of lines required to print a value
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)
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)
x |
( |
colwidths |
( |
max_width |
( |
fontspec |
( |
col_gap |
( |
The number of lines needed to render the object x
.
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.
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
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
obj |
( |
value |
( |
Absent a class-specific method, this function returns 0, indicating no always-repeated columns.
An integer.
This number does not include row labels, the repetition of which is handled separately.
mpf <- basic_matrix_form(mtcars) num_rep_cols(mpf) lmpf <- basic_listing_mf(mtcars) num_rep_cols(lmpf)
mpf <- basic_matrix_form(mtcars) num_rep_cols(mpf) lmpf <- basic_listing_mf(mtcars) num_rep_cols(lmpf)
Activate font state
open_font_dev(fontspec, silent = FALSE) close_font_dev() debug_font_dev() undebug_font_dev()
open_font_dev(fontspec, silent = FALSE) close_font_dev() debug_font_dev() undebug_font_dev()
fontspec |
( |
silent |
( |
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 info
fontspec
(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.
open_font_dev
returns a logical value indicating whether a new pdf device was opened.
close_font_dev
, debug_font_dev
and undebug_font_dev
return NULL
.
In all cases the value is returned invisibly.
open_font_dev(font_spec("Times")) nchar_ttype("Hiya there", font_spec("Times")) close_font_dev()
open_font_dev(font_spec("Times")) nchar_ttype("Hiya there", font_spec("Times")) close_font_dev()
Pad a string and align within string
padstr(x, n, just = list_valid_aligns(), fontspec = font_spec())
padstr(x, n, just = list_valid_aligns(), fontspec = font_spec())
x |
( |
n |
( |
just |
( |
fontspec |
( |
x
, padded to be a string of length n
.
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)
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)
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
.
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 )
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 )
pagdf |
( |
rlpp |
( |
lpp_or_cpp |
( |
context_lpp_or_cpp |
( |
min_siblings |
( |
nosplitin |
( |
verbose |
( |
row |
( |
have_col_fnotes |
( |
div_height |
( |
col_gap |
( |
has_rowlabels |
( |
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.
A list
containing a vector of row numbers, broken up by page.
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 row
The 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
and start + lpp
(start + cpp
) would be < start
after decrementing
Retain pagination index
If pagination point was less than NROW(tt)
(ncol(tt)
), set
start
to pos + 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 siblings
pagination would occur within a sub-table listed in nosplitin
mypgdf <- basic_pagdf(row.names(mtcars)) paginds <- pag_indices_inner(mypgdf, rlpp = 15, min_siblings = 0) lapply(paginds, function(x) mtcars[x, ])
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
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 )
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 )
row |
( |
nm |
( |
lab |
( |
rnum |
( |
pth |
( |
sibpos |
( |
nsibs |
( |
extent |
( |
colwidths |
( |
repext |
( |
repind |
( |
indent |
( |
rclass |
( |
nrowrefs |
( |
ncellrefs |
( |
nreflines |
( |
force_page |
( |
page_title |
( |
trailing_sep |
( |
fontspec |
( |
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
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) )
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) )
page_type |
( |
landscape |
( |
font_family |
( |
font_size |
( |
lineheight |
( |
margins |
( |
pg_width |
( |
pg_height |
( |
fontspec |
( |
A named list containing LPP (lines per page) and CPP (characters per page) elements suitable for use by the pagination machinery.
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)
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)
List supported named page types.
page_types() page_dim(page_type)
page_types() page_dim(page_type)
page_type |
( |
page_types
returns a character vector of supported page types
page_dim
returns the dimensions (width, then height) of the selected page type.
page_types() page_dim("a4")
page_types() page_dim("a4")
These functions perform or diagnose bi-directional pagination on an object.
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), 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), 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), fontspec = fontspec), 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), ... )
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), 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), 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), fontspec = fontspec), 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), ... )
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 |
( |
verbose |
( |
page_num |
( |
... |
additional parameters passed to individual methods. |
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.
paginate_indices
returns a list
with two elements of the same length: pag_row_indices
and pag_col_indices
.
paginate_to_mpfs
returns a list
of MatrixPrintForm
objects representing each individual page after
pagination (including forced pagination if necessary).
diagnose_pagination
returns a list
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.
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.
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
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
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 row
The 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
and start + lpp
(start + cpp
) would be < start
after decrementing
Retain pagination index
If pagination point was less than NROW(tt)
(ncol(tt)
), set
start
to pos + 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 siblings
pagination would occur within a sub-table listed in nosplitin
MatrixPrintForm
of an objectRow names are also considered a column for the output.
propose_column_widths(x, indent_size = 2, fontspec = font_spec())
propose_column_widths(x, indent_size = 2, fontspec = font_spec())
x |
( |
indent_size |
( |
fontspec |
( |
A vector of column widths based on the content of x
for use in printing and pagination.
mf <- basic_matrix_form(mtcars) propose_column_widths(mf)
mf <- basic_matrix_form(mtcars) propose_column_widths(mf)
Create a row for a referential footnote information data frame
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 )
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 )
row_path |
( |
col_path |
( |
row |
( |
col |
( |
symbol |
( |
ref_index |
( |
msg |
( |
max_width |
( |
A single row data frame with the appropriate columns.
This function is used within format_value()
to prepare numeric values within
cells for formatting and display.
round_fmt(x, digits, na_str = "NA")
round_fmt(x, digits, na_str = "NA")
x |
( |
digits |
( |
na_str |
( |
This function combines the rounding behavior of R's standards-compliant round()
function (see the Details section of that documentation) with the strict decimal display
of sprintf()
. The exact behavior is as follows:
If x
is NA
, the value of na_str
is returned.
If x
is non-NA
but digits
is NA
, x
is converted to a character and returned.
If x
and digits
are both non-NA, round()
is called first, and then sprintf()
is used to convert the rounded value to a character with the appropriate number of trailing
zeros enforced.
A character value representing the value after rounding, containing any trailing zeros
required to display exactly digits
elements.
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).
format_value()
, round()
, sprintf()
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, 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)
Transform a vector of spans (with duplication) into a visibility vector
spans_to_viscell(spans)
spans_to_viscell(spans)
spans |
( |
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.
A logical vector the same length as spans
indicating whether the contents of a string vector
with those spans is valid.
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.
spans_to_viscell(c(2, 2, 2, 2, 1, 3, 3, 3))
spans_to_viscell(c(2, 2, 2, 2, 1, 3, 3, 3))
wrap string given a Truetype font
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 )
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 )
str |
( |
width |
( |
fontspec |
( |
min_ok_chars |
( |
collapse |
( |
wordbreak_ok |
( |
str
, broken up into a word-wrapped vector
Spread an integer to a given length
spread_integer(x, len)
spread_integer(x, len)
x |
( |
len |
( |
If x
is a scalar whole number value (see is.wholenumber()
), the value x
is repeated len
times.
Otherwise, an error is thrown.
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)
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)
sprintf
format stringSpecify text format via a sprintf
format string
sprintf_format(format)
sprintf_format(format)
format |
( |
A formatting function which wraps and applies the specified sprintf
-style format
to string format
.
fmtfun <- sprintf_format("(N=%i") format_value(100, format = fmtfun) fmtfun2 <- sprintf_format("%.4f - %.2f") format_value(list(12.23456, 2.724))
fmtfun <- sprintf_format("(N=%i") format_value(100, format = fmtfun) fmtfun2 <- sprintf_format("%.4f - %.2f") format_value(list(12.23456, 2.724))
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.
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
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
obj |
( |
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<-
returns obj
with the new table_inset value applied recursively to it and
all its subtables.
Useful functions for writing tests and examples, and a starting point for
more sophisticated custom matrix_form
methods.
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() )
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() )
df |
( |
indent_rownames |
( |
parent_path |
( |
ignore_rownames |
( |
add_decoration |
( |
fontspec |
( |
split_labels |
( |
data_labels |
( |
num_rep_cols |
( |
keycols |
( |
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
).
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.
basic_listing_mf()
: Create a MatrixPrintForm
object from data frame df
that
respects the default formats for a listing object.
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))
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 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 = "+"
).
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 )
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 )
x |
( |
... |
additional parameters passed to individual methods. |
widths |
( |
tf_wrap |
( |
max_width |
( |
col_gap |
( |
hsep |
( |
fontspec |
( |
ttype_ok |
( |
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.
A character string containing the ASCII rendering of the table-like object represented by x
.
mform <- basic_matrix_form(mtcars) cat(toString(mform))
mform <- basic_matrix_form(mtcars) cat(toString(mform))
data.frame
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).
var_labels(x, fill = FALSE)
var_labels(x, fill = FALSE)
x |
( |
fill |
( |
a named character vector of variable labels from x
, with names corresponding
to variable names.
x <- iris var_labels(x) var_labels(x) <- paste("label for", names(iris)) var_labels(x)
x <- iris var_labels(x) var_labels(x) <- paste("label for", names(iris)) var_labels(x)
data.frame
Remove label
attribute from all variables in a data frame.
var_labels_remove(x)
var_labels_remove(x)
x |
( |
x
with its variable labels stripped.
x <- var_labels_remove(iris)
x <- var_labels_remove(iris)
data.frame
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
.
var_labels(x) <- value
var_labels(x) <- value
x |
( |
value |
( |
x
with modified variable labels.
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 }
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 }
data.frame
Relabel a subset of the variables.
var_relabel(x, ...)
var_relabel(x, ...)
x |
( |
... |
name-value pairs, where each name corresponds to a variable name in
|
A copy of x
with labels modified according to ...
x <- var_relabel(iris, Sepal.Length = "Sepal Length of iris flower") var_labels(x)
x <- var_relabel(iris, Sepal.Length = "Sepal Length of iris flower") var_labels(x)
Find column indices for vertical pagination
vert_pag_indices( obj, cpp = 40, colwidths = NULL, verbose = FALSE, rep_cols = 0L, fontspec, nosplitin = character() )
vert_pag_indices( obj, cpp = 40, colwidths = NULL, verbose = FALSE, rep_cols = 0L, fontspec, nosplitin = character() )
obj |
( |
cpp |
( |
colwidths |
( |
verbose |
( |
rep_cols |
( |
fontspec |
( |
nosplitin |
( |
A list
partitioning the vector of column indices into subsets for 1 or more horizontally paginated pages.
mf <- basic_matrix_form(df = mtcars) colpaginds <- vert_pag_indices(mf, fontspec = font_spec()) lapply(colpaginds, function(j) mtcars[, j, drop = FALSE])
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
with_label(x, label)
with_label(x, label)
x |
( |
label |
( |
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
.
x <- with_label(c(1, 2, 3), label = "Test") obj_label(x)
x <- with_label(c(1, 2, 3), label = "Test") obj_label(x)
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.
wrap_string(str, width, collapse = NULL, fontspec = font_spec()) wrap_txt(str, width, collapse = NULL, fontspec = font_spec())
wrap_string(str, width, collapse = NULL, fontspec = font_spec()) wrap_txt(str, width, collapse = NULL, fontspec = font_spec())
str |
( |
width |
( |
collapse |
( |
fontspec |
( |
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.
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
).
wrap_txt()
: Deprecated function. Please use wrap_string()
instead.
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)
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)