Version: | 0.9-1 |
Date: | 2024-01-26 |
Title: | Presentation-Quality Tables, Displayed Using 'ggplot2' |
Author: | Richard Raubertas [aut, cre] |
Maintainer: | Richard Raubertas <rrprf@emvt.net> |
License: | GPL (≥ 3) |
Imports: | ggplot2 (≥ 3.4.0), tables, graphics, grDevices, stats, tools, utils, grid |
Suggests: | ggtext, gridtext, quadprog, xtable, knitr, rmarkdown |
Description: | Presentation-quality tables are displayed as plots on an R graphics device. Although there are other packages that format tables for display, this package is unique in combining two features: (a) It is aware of the logical structure of the table being presented, and makes use of that for automatic layout and styling of the table. This avoids the need for most manual adjustments to achieve an attractive result. (b) It displays tables using 'ggplot2' graphics. Therefore a table can be presented anywhere a graph could be, with no more effort. External software such as LaTeX or HTML or their viewers is not required. The package provides a full set of tools to control the style and appearance of tables, including titles, footnotes and reference marks, horizontal and vertical rules, and spacing of rows and columns. Methods are included to display matrices; data frames; tables created by R's ftable(), table(), and xtabs() functions; and tables created by the 'tables' and 'xtable' packages. Methods can be added to display other table-like objects. A vignette is included that illustrates usage and options available in the package. |
URL: | https://github.com/rrprf/tablesgg |
LazyData: | yes |
VignetteBuilder: | knitr |
NeedsCompilation: | no |
Packaged: | 2024-01-26 20:49:43 UTC; rfr |
Repository: | CRAN |
Date/Publication: | 2024-01-27 01:10:02 UTC |
Presentation-Quality Tables, Displayed Using ggplot2
Description
Presentation-quality tables are displayed as plots on an R graphics device. Although there are other packages that format tables for display, this package is unique in combining two features: (a) It is aware of the logical structure of the table being presented, and makes use of that for automatic layout and styling of the table. This avoids the need for most manual adjustments to achieve an attractive result. (b) It displays tables using ggplot2 graphics. Therefore a table can be presented anywhere a graph could be, with no more effort. External software such as LaTeX or HTML or their viewers is not required.
Methods are included to display matrices; data frames; tables created by R's
ftable
, table
, and xtabs
functions; and tables
created by the tables and xtable packages. Methods can be
added to display other table-like objects.
Other package features:
A full set of tools is provided to control the appearance of tables, including titles, footnotes and reference marks, horizontal and vertical rules, and spacing of rows and columns. Many properties can be set automatically by specifying styles. Default styles are included, and the user can define custom styles.
There are tools for low-level manipulation of the appearance of individual table elements if desired.
All sizes and dimensions in displayed tables are specified in physical units (points for font size, millimeters for everything else). Therefore a plotted table has a well-defined physical size, independent of the size of the graphics device on which it is displayed. The user can easily increase or decrease the displayed size by a scale factor, maintaining the relative proportions of table elements.
Since the plotted tables are ordinary
ggplot
objects, the facilities of ggplot2 and its various extension packages are available to modify or manipulate the table. For example, the table can be inserted as an image within another plot.
A vignette is included that illustrates usage and options available in the package.
Extract a Subset of a texttable
Object
Description
Extract a subset of a textTable
object, creating a new table with
fewer and/or rearranged rows and columns.
Usage
## S3 method for class 'textTable'
x[i, j, drop=FALSE]
Arguments
x |
An object of S3 class |
i , j |
Logical or numeric indexing arguments used as subscripts with respect to the augmented row-column grid of the table. See DETAILS. |
drop |
Ignored (always treated as FALSE). |
Details
This function extracts, deletes, or rearranges subsets of the rows and
columns of a table. It is similar to subsetting an ordinary matrix, but
with restrictions required to ensure that the resulting object is still a
valid textTable
:
1. Indexing is with respect to the augmented row-column grid of the
table, in which all parts of the table (body, headers, and annotation) are
included. See ?textTable
for a description of table parts, and
?adim
for a description of the augmented grid. The summary
method for a textTable
shows the dimensions of each part.
2. The first index argument, i
, cannot itself be a matrix.
3. Indexing cannot be used to move rows or columns between different parts of the table (e.g. between body and headers, or between headers and annotation).
Helper functions arow
and acol
can be used to get the
augemented row and column numbers spanned by different table parts. See
the examples.
Value
An object of S3 class textTable
.
See Also
Examples
ttbl <- textTable(iris2_tab)
plot(ttbl)
# Remove the first column header row ("Flower part"), and reverse the
# order of the "Sepal" and "Petal" sets of columns:
subttbl <- ttbl[-1, c(1,2,5,6,3,4)]
plot(subttbl)
# Use helper functions 'arow', 'acol' to specify indices based on
# table structure:
i <- arow(ttbl, "colhead")[1] # row number of first column header row
j1 <- acol(ttbl, "rowhead") # column numbers for row header
j2 <- acol(ttbl, "colhead") # column numbers for column header
subttbl2 <- ttbl[-i, c(j1, j2[c(3,4,1,2)])]
identical(subttbl, subttbl2)
Column Numbers Within the Augmented Row-Column Grid for a Table
Description
Return the column numbers associated with a specified table part or element, or with a set of column header values, within the augmented row-column grid of a table.
Usage
acol(x, id=NULL, hpath=NULL)
Arguments
x |
A |
id |
Character scalar containing the ID of a single table part, block, entry,
or hvrule. (If |
hpath |
Character vector with length between 0 and the number of layers in the
column header. The |
Details
See the documentation for adim
for more information about the
augmented row-column grid of a table.
Only one of arguments id
and hpath
should be specified.
id
is searched for first among table parts (the only thing
available for a textTable
), then blocks, entries, and hvrules, in
that order. The search stops at the first match. It is an error if
id
is not found in any of these.
hpath
is short for "header path". It is used to obtain column
numbers associated with specified combinations of values of the column
header variables. Suppose there are L
layers of column headers.
If the length of hpath
is less than L
, NA values are added
at the end to reach that length. The function returns the intersection of
the column numbers for which the i
-th outermost of the header
layers equals the i
-th element of hpath
. An NA in
hpath
is taken to match all values in the correponding layer of
column headers. Thus, if L == 4
and hpath=c("a", NA, "c")
,
the function will return the column numbers for which the outermost column
header has a value of "a" _and_ the third outermost has a value of "c".
If no column has the combination of values specified by hpath
then
the returned vector will have length 0.
Since hpath
refers to values of column header variables, it cannot
be used to get column numbers associated with table annotation, or with
the row header. (Use id
instead.)
Value
A numeric vector containing column numbers within the table's augmented
row-column grid. The column numbers are those partially or completely
occupied by the cells associated with id
or hpath
. They
will be increasing but not necessarily consecutive.
The returned vector may have length 0 if id
refers to a table part
or block that spans no columns, or if hpath
matches no set of
column header values.
Note that for a vertical hvrule (vrule), the "column number" is actually a
half-integer, bracketed by the table column numbers between which the
vrule runs. For example, if the vrule runs between table columns 3 and 4,
the returned value will be c(3.5)
.
See Also
adim
to get the dimensions of the augmented row-column grid;
arow
for the corresponding operation on rows;
ids
Examples
ttbl <- textTable(iris2_tab, title=c("Title 1", "2nd title"), foot="Foot")
plt <- plot(ttbl)
acol(plt, id="title") # block "title" spans all columns
acol(plt, id="body,4,2") # single entry
# Remove the columns for "Petal" measurements (a value in column
# header layer 2):
plot(ttbl[, -acol(ttbl, hpath=c(NA, "Petal"))])
# Remove the "Length" measurements (a value in column header layer 3):
plot(ttbl[, -acol(ttbl, hpath=c(NA, NA, "Length"))])
# Remove the "Length" measurements just for "Petal":
plot(ttbl[, -acol(ttbl, hpath=c(NA, "Petal", "Length"))])
Define a New Block of Cells in a Table
Description
Define a new block (rectangular set of cells) in a table. The location and graphical properties of the block are specified explicitly, rather than being generated automatically from the logical structure of the table and a style.
Usage
addBlock(x, arows, acols, id, props=NULL, enabled=FALSE)
Arguments
x |
A plotted table ( |
arows , acols |
Numeric vectors specifying the cells contained in the block, with respect
to the augmented row-column grid of the table. The block includes the
cells in row numbers from |
id |
Optional character string giving the ID to be assigned to the new block.
It is an error if there is already a block with this ID in |
props |
Optional |
enabled |
Logical scalar, whether the new block is to be enabled for display. The default is FALSE. |
Details
Normally blocks are defined automatically, based on the logical structure of the table and the style selected by the user. This function allows additional blocks to be defined "manually", explicitly specifying their position and span in terms of row and column numbers.
There are two typical situations in which one would want to define a new
block. The first is to highlight a specific set of cells in the table
visually, by shading or a border. For that purpose one should specify
enabled=TRUE
(so the block will be displayed) and perhaps
props
(for non-default graphical properties).
The second reason to define a new block is to use its ID as a quick way to
refer to the entries within it, for example to set their graphical
properties using props<-
. In that case enabled
for the
block should be FALSE, since the block itself is not to be displayed.
Row and column numbers are with respect to the augmented row-column grid
of the table. See ?adim
for more more information about this grid.
The helper functions arow
and acol
can be used to specify
arguments arows
and acols
in terms of table parts or
previously defined blocks.
Graphical properties for blocks defined by this function will not be
changed if a new block style is applied to the plotted table. Use one of
the props<-
functions instead.
There is no way to remove or undefine a block, other than recreating the
plotted table object from scratch. However they can be disabled using a
props<-
function, and then will not be displayed.
Value
A plotted table object like x
, with the new block defined.
See Also
arow
, acol
, adim
,
element_block
Examples
plt <- plot(iris2_tab, title="The iris data",
subtitle="Summary statistics by species")
plt <- addBlock(plt, arows=c(8, 9), acols=c(3, 4), id="new_block",
props=element_block(border_color="red", border_size=1.0),
enabled=TRUE)
plt
# Can refer to the new block by its ID:
props(plt, id="new_block") <- element_entry(fontface=3) # italics
plt
Add a Horizontal or Vertical Rule (Hvrule) to a Table
Description
Add a horizontal or vertical rule (hvrule) to a table. The location, span, and graphical properties of the hvrule are specified explicitly, rather than being generated automatically from the logical structure of the table and a style.
Usage
addHvrule(x, direction, arows, acols, id, props=NULL, enabled=TRUE)
Arguments
x |
A plotted table ( |
direction |
Character string specifying whether the rule is to be horizontal
( |
arows , acols |
Numeric vectors specifying the location and span of the hvrule, with
respect to the augmented row-column grid of the table. For an hrule,
|
id |
Character string giving the ID to be assigned to the new hvrule. It is an
error if there is already an hvrule with this ID in |
props |
Optional |
enabled |
Logical scalar, whether the new hvrule is to be enabled for display. The default is TRUE. |
Details
Normally hvrules are generated automatically, based on the logical structure of the table and the style selected by the user. This function allows additional hvrules to be added "manually", explicitly specifying their position and span in terms of row and column numbers.
Row and column numbers are with respect to the augmented row-column grid
of the table. See ?adim
for more more information about this grid.
The helper functions arow
and acol
can be used to specify
arguments arows
and acols
in terms of table parts or
previously defined blocks.
For an hrule
, the default for acols
is to span all table
columns. For a vrule
, the default for arows
is to span the
rows containing the body and column headers, but not the annotation.
Graphical properties for hvrules defined by this function will not be
changed if a new hvrule style is applied to the plotted table. Use one of
the props<-
functions instead.
There is no way to remove an hvrule, other than recreating the plotted
table object from scratch. However they can be disabled using a
props<-
function, and then will not be displayed or take up any
space.
Value
A plotted table object like x
, with the new hvrule added.
See Also
arow
, acol
, adim
,
element_hvrule
Examples
plt <- plot(iris2_tab, title="The iris data")
plt <- addHvrule(plt, direction="vrule", acols=4.5, arows=arow(plt, "body"),
id="new_vrule",
props=element_hvrule(linetype=2, color="red"), enabled=TRUE)
plt
# Can refer to the new hvrule by its ID:
props(plt, id="new_vrule") <- element_hvrule(enabled=FALSE) # don't display it
plt
Add a Reference Mark to Entries in a Table
Description
Add a reference mark (a symbol placed before or after entry text to indicate cross-references; e.g. for footnotes) to entries in a table.
Usage
addRefmark(x, mark, before=character(0), after=character(0),
parts=NULL, raise, ...)
Arguments
x |
A |
mark |
Character string containing the reference mark. |
before , after |
Character strings containing regular expressions (see |
parts |
Optional character vector listing table parts. If specified, only entries
in those parts will be matched against |
raise |
Logical scalar. If TRUE, the reference mark will be displayed as a
superscript, using |
... |
Additional arguments passed to |
Details
Reference marks are placed at the beginning or end of an entry's text. If
raise
is TRUE they will be displayed as superscripts. This is
implemented by converting the text to make use of R's plotmath
facility to create the superscript. A limitation of plotmath
is
that it ignores newline characters within text. Therefore raised
reference marks will not work with multi-line entries, and a warning will
be issued.
In addition to using numbers, letters, or asterisk as reference marks, traditional symbols can be specified by their unicode values: dagger ("\u2020"), double dagger ("\u2021"), paragraph symbol ("\u00B6"), section symbol ("\u00A7"), and double vertical bars ("\u2016"). However, unicode symbols may not be available for all OS's or graphics devices.
With this function the user identifies the entries to be marked by
searching the entry text itself, via regular expressions before
and/or after
. For plotted tables (pltdTable
objects), an
alternative way to add reference marks is to use one of the props<-
functions to assign an element_refmark
to it. They allow selection
of entries using other descriptors.
Value
An object like x
. The text of table cells/entries selected by
before
and after
will be modified to include the reference
mark, and if raise
is TRUE, those cells/entries will be flagged to
indicate that they should be treated as plotmath
expressions.
See Also
Examples
# Add reference marks to a 'textTable':
ttbl <- textTable(iris2_tab, foot="sd = standard deviation")
ttbl <- addRefmark(ttbl, mark="a", before="sd =", after="sd$")
plot(ttbl)
# Add reference marks to a 'pltdTable':
plt <- plot(textTable(iris2_tab, foot="sd = standard deviation"))
plt <- addRefmark(plt, mark="*", before="sd =", after="sd$")
plt
# To add a reference mark to just the *first* appearance of "sd", use
# 'propsa<-' instead:
plt <- plot(textTable(iris2_tab, foot="sd = standard deviation"))
plt <- addRefmark(plt, mark="a", before="sd =")
propsa(plt, arows=arow(plt, hpath=c("setosa", "sd")),
acols=acol(plt, "rowhead")[2]) <- element_refmark("a", side="after")
plt
Add a Reference Mark to a Character Vector or Matrix
Description
Utility function to add a reference mark to each element of a character vector or matrix. This is an internal function, not intended to be called by package users.
Usage
add_refmark(text, textspec, mark, side, raise)
Arguments
text |
Character vector or matrix of text strings to be marked. |
textspec |
Character vector or matrix, parallel to |
mark |
Character string to be used as the reference mark. |
side |
On which side of the text should the reference mark be placed, "before" or "after". |
raise |
Logical scalar. If TRUE, the reference mark will be displayed as a
superscript, using |
Details
If raise
is TRUE, every element in the returned text will contain
either plotmath or markdown notation. If a text string was originally
"plain", the default is to use markdown if the package option
allowMarkdown
is TRUE, and plotmath otherwise.
It is an error if a "plain" text string contains newline (\n
)
characters but needs to be converted to plotmath to add a reference mark.
(plotmath
ignores newline characters.)
If raise
is FALSE, the textspec
value for each string is the
same as on input.
Value
List with components text
and textspec
. The first will be a
character vector or matrix like input text
, updated to include the
reference mark in each string.
Component textspec
will be a character vector or matrix with the
same shape as text
, and value "plain", "plotmath", or "markdown",
according to the contents of text
after adding the reference mark.
Dimensions of the Augmented Row-Column Grid for a Table
Description
Return the dimensions of the augmented row-column grid for a table. Along with rows and columns associated with the body of the table, the augmented grid includes rows for each title, subtitle, and foot line, and rows and columns associated with the column and row headers.
Usage
adim(x)
Arguments
x |
A table, in any of the forms used within the |
Details
It is common to think of the number of rows and columns in a table as referring to the _body_ of the table. However in this package the grid of rows and columns in the body of a table is expanded into an _augmented row-column grid_, by adding a row for each title, subtitle, and foot line; a row for each layer of column headers; a row for each _interior_ row header entry; and a column for each (non-interior) layer of row headers. The augmented grid is numbered from the upper left, so column numbers increase from left to right, and row numbers from top to bottom. Title, subtitle, and foot lines, and interior row header entries span all the columns of the grid.
This function returns the dimensions of the augmented grid.
Disabled entries are included in counting rows and columns.
The function summary
gives the dimensions of individual parts
within a table.
Value
A two-element numeric vector containing (number of rows, number of columns).
See Also
summary.textTable
, summary.pltdTable
Examples
ttbl <- textTable(iris2_tab, title="Summary statistics for the iris data")
adim(ttbl)
plt <- plot(ttbl)
adim(plt)
Identify Adjacent Blocks of Table Cells
Description
For each block of table cells in a tblBlocks
object, identify the
other blocks that are adjacent to it on each side. This is an internal
utility function, not intended to be called by package users.
Usage
adjacent_blocks(x)
Arguments
x |
A |
Details
A block B is considered adjacent to block A if (a) the blocks do not intersect (have no cells in common); and (b) the blocks touch along at least part of one edge (they span overlapping sets of rows in adjacent columns, or overlapping sets of columns in adjacent rows).
It requires storage and time proportional to the square of the number of blocks. For realistic tables this is not likely to be a problem.
Value
A list array with one row per block in x
, and four columns. The
rows are named by the block id
, and the columns as "top", "right",
"bottom", and "left". Element [[i, j]]
is a character vector
containing the ID's of all blocks that are adjacent to block i
on
side j
. If there are no adjacent blocks, the element is
character(0)
.
See Also
Horizontal and Vertical Dimensions of a Rectangle after Rotation
Description
Calculate the horizontal and vertical dimensions of a rectangle after
rotation by angle theta
(in degrees). This is an internal
function, not intended to be called by package users.
Usage
angle_adj(hsize, vsize, theta)
Arguments
hsize , vsize |
Numeric scalars, the width and height of a rectangle oriented parallel to the coordinate axes, with one corner at the origin. |
theta |
Rotation angle, in degrees. |
Value
Two-element vector with the new width and height, with respect to the original axes, of the rotated rectangle.
Apply a Scale Factor to Table Elements
Description
Apply a scale factor to table elements, to change their overall displayed size. This is an internal function, not intended to be called by package users.
Usage
apply_scale(x, type, scale)
Arguments
x |
A data frame containing table elements (entries, hvrules, or blocks). |
type |
Character string with the element type for |
scale |
Numeric scalar; a multiplier used to increase or decrease the displayed
size of all the elements in |
Value
A data frame like x
, with the columns containing scalable graphical
properties multiplied by scale
.
See Also
grSpecs
specifies which graphical properties are scalable
for each element type.
Apply a Style to Table Elements
Description
Apply a style to assign graphical properties to table elements. This is an internal function not intended to be called by package users.
Usage
apply_style(x, style, replace, setEnabled, unstyled, base_style)
Arguments
x |
A data frame containing table elements (entries, hvrules, or blocks). |
style |
A |
replace |
If FALSE only graphical properties not already present as columns in
|
setEnabled |
If TRUE then column |
unstyled |
Character string indicating how to handle elements for which |
base_style |
A |
Details
Table elements include entries, blocks, and hvrules. If x
contains
table entries, the element_type
for style
should be "entry".
If x
contains table blocks, element_type
may be either
"block" or "hvrule". In the latter case a set of hvrules will be
generated, one for each of the four sides of each block. Then
style
will be used to assign graphical properties to those hvrules.
The graphical properties available for an element, and their types, are
defined in function grSpecs
and documented in ?elements
.
See styleObj
for information about how a style is specified, and
how it is applied to elements. Note that individual style specifications
(rows) in style
are applied to x
in order. If an element
matches more than one style
row, the last matching row will
override the earlier ones.
NA values after evaluating condition
expressions in a style:
styleObj
objects contain contain character fields that are
evaluated as expressions with respect to columns of x
. The fields
are called condition
for entry and block styles, and
block_condition
and adjacent_condition
for hvrule styles.
Each expression must evaluate to a logical scalar or vector with one value
per row of x
. If an expression evaluates to NA for a row of
x
it is treated as FALSE for that row–the reason to not throw an
error is to make it easier to manually add blocks or hvrules by position
only. (Note that this is different from the case where the condition
expression itself, before evaluation, is NA. The latter is treated as
evaluating to TRUE for all rows of x
.)
Value
A data frame. It has one row per table element and the same columns as
x
, plus additional or updated columns containing the graphical
properties to use for each element, plus a column style_row
(the
number of the last row in style
that the entry matched, or NA if it
matched none).
See Also
styleObj
; grSpecs
, apply_scale
Row Numbers Within the Augmented Row-Column Grid for a Table
Description
Return the row numbers associated with a specified table part or element, or with a set of row header values, within the augmented row-column grid of a table.
Usage
arow(x, id=NULL, hpath=NULL)
Arguments
x |
A |
id |
Character scalar containing the ID of a single table part, block, entry,
or hvrule. (If |
hpath |
Character vector with length between 0 and the number of layers in the row
header. The |
Details
See the documentation for adim
for more information about the
augmented row-column grid of a table.
Only one of arguments id
and hpath
should be specified.
id
is searched for first among table parts (the only thing
available for a textTable
), then blocks, entries, and hvrules, in
that order. The search stops at the first match. It is an error if
id
is not found in any of these.
hpath
is short for "header path". It is used to obtain row numbers
associated with specified combinations of values of the row header
variables. Suppose there are L
layers of row headers. If the
length of hpath
is less than L
, NA values are added at the
end to reach that length. The function returns the intersection of the
row numbers for which the i
-th outermost of the header layers
equals the i
-th element of hpath
. An NA in hpath
is
taken to match all values in the correponding layer of row headers. Thus,
if L == 4
and hpath=c("a", NA, "c")
, the function will
return the row numbers for which the outermost row header has a value of
"a" _and_ the third outermost has a value of "c". If no row has the
combination of values specified by hpath
then the returned vector
will have length 0.
Since hpath
refers to values of row header variables, it cannot be
used to get row numbers associated with table annotation, or with the
column header. (Use id
instead.)
Value
A numeric vector containing row numbers within the table's augmented
row-column grid. The row numbers are those partially or completely
occupied by the cells associated with id
or hpath
. They
will be increasing but not necessarily consecutive.
The returned vector may have length 0 if id
refers to a table part
or block that spans no rows, or if hpath
matches no set of row
header values.
Note that for a horizontal hvrule (hrule), the "row number" is actually a
half-integer, bracketed by the table row numbers between which the hrule
runs. For example, if the hrule runs between table rows 3 and 4, the
returned value will be c(3.5)
.
See Also
adim
to get the dimensions of the augmented row-column grid;
acol
for the corresponding operation on columns;
ids
Examples
ttbl <- textTable(iris2_tab, title=c("Title 1", "2nd title"), foot="Foot")
plt <- plot(ttbl)
arow(plt, id="title") # block "title" spans first two rows
arow(plt, id="body,4,2") # single entry
# Remove the first line of the column header:
plot(ttbl[-arow(ttbl, id="colhead")[1], ])
# Remove the "versicolor" species (a value in row header layer 1):
plot(ttbl[-arow(ttbl, hpath=c("versicolor")), ])
# Remove the means for all species (a value in row header layer 2):
plot(ttbl[-arow(ttbl, hpath=c(NA, "mean")), ])
# Remove the mean just for the versicolor species:
plot(ttbl[-arow(ttbl, hpath=c("versicolor", "mean")), ])
Promote a Data Frame to Another Object Class
Description
Promote a data frame to another object class, or do validity checking of such an object. This is an internal function not intended to be called by package users.
Usage
as.dfObj(x, objClass)
Arguments
x |
An object inheriting from |
objClass |
Character string giving the class of the object to be returned/ checked. One of: "tblEntries", "tblBlocks", "prEntries", "prHvrules", "prBlocks". |
Details
This is a backend to the as.<objClass>
functions.
The purpose of this function is to reduce code repetition by factoring out common tasks when promoting a data frame to one of the data frame-based objects in the package (or checking the validity of such objects).
For all objects, row names are set equal to the id
column.
Value
An object with S3 classes given by objClass
and "data.frame".
See Also
tblEntries
, tblBlocks
,
prEntries
, prHvrules
, prBlocks
;
dfSpecs
returns info about the fields required for each
object class.
Promote a Data Frame to a prblocks
Object
Description
Promote a data frame to a prBlocks
object, containing plot-ready
blocks for a table. This is an internal function not intended to be
called by package users.
Usage
as.prBlocks(x)
Arguments
x |
An object inheriting from |
Details
Normally plot-ready blocks are created from a tblBlocks
object via
function prBlocks
. This function allows them to be created or
edited directly in a data frame, without necessarily using a predefined
style.
Columns arow1
, arow2
, acol1
and acol2
refer to
row and column numbers in the augmented row-column grid of the table; see
adim
for more information.
The graphical properties required for a plot-ready block, and their types,
are defined in object grSpecs
.
If column enabled
was not present in x
it will be added,
with value FALSE for all blocks. Attributes current_scale
,
rowgroupSize
, and rowheadInside
will be added if not
present, with values 1.0, NA, and NA, respectively.
If x
is already a prBlocks
object, this function does some
validity checks. If x
is NULL, a valid but empty prBlocks
object is returned.
Value
An object of S3 classes prBlocks
, tblBlocks
, and
data.frame
. See function prBlocks
for a full description of
the class.
See Also
Promote a Data Frame to a prentries
Object
Description
Promote a data frame to a prEntries
object, containing plot-ready
table entries. This is an internal function not intended to be called by
package users.
Usage
as.prEntries(x)
Arguments
x |
An object inheriting from |
Details
Normally plot-ready entries are created from a tblEntries
object
via function prEntries
. This function allows them to be created or
edited directly in a data frame, without necessarily using a predefined
style.
Columns arow1
, arow2
, acol1
and acol2
refer to
row and column numbers in the augmented row-column grid of the table; see
adim
for more information.
The graphical properties required for a plot-ready entry, and their types,
are defined in object grSpecs
.
If not present, logical column enabled
will be added with value
TRUE for all entries whose text
is not NA or empty. If attribute
current_scale
is not present, it will be added with a value of 1.0.
If attribute rowheadInside
is not present, it will be added with a
value of NA.
If x
is already a prEntries
object, this function does some
validity checks. If x
is NULL, a valid but empty prEntries
object is returned.
Value
An object of S3 classes prEntries
, tblEntries
, and
data.frame
. See function prEntries
for a full description
of the class.
See Also
Promote a Data Frame to a prhvrules
Object
Description
Promote a data frame to a prHvrules
object, containing plot-ready
hvrules for a table. This is an internal function not intended to be
called by package users.
Usage
as.prHvrules(x)
Arguments
x |
An object inheriting from |
Details
Normally plot-ready hvrules are created from a tblBlocks
object via
function prHvrules
. This function allows them to be created or
edited directly in a data frame, without necessarily using a predefined
style.
Columns arow1
, arow2
, acol1
and acol2
refer to
row and column numbers in the augmented row-column grid of the table; see
adim
for more information.
For an hrule (horizontal rule), arow1
and arow2
should be
equal to each other and to a half-integer; the hrule will be inserted
between table row numbers that bracket the value. (For example,
arow1 = arow2 = 3.5
means the hrule will be inserted between rows 3
and 4.) acol1
and acol2
should be integers that indicate
the first and last columns to be spanned by the hrule.
For a vrule (vertical rule) the specification is similar, but with the
roles of arow*
and acol*
reversed.
If column enabled
was not present in x
it will be added,
with value FALSE for all hvrules.
If x
is already a prHvrules
object, this function does some
validity checks. If x
is NULL, a valid but empty prHvrules
object is returned.
Value
An object of S3 class prHvrules
and data.frame
. See
function prHvrules
for a full description of the class.
See Also
Promote a Data Frame to a tblblocks
Object
Description
Promote a data frame to a tblBlocks
object. This is an internal
function not intended to be called by package users.
Usage
as.tblBlocks(x)
Arguments
x |
A data frame, with each row representing one table block. See
|
Details
Normally a standard set of structure-based blocks is created from a
tblEntries
object via function tblBlocks
. This function
allows blocks to be created or edited directly in a data frame.
A block is simply a rectangular set of contiguous table cells. Any number
of blocks may be defined, and blocks may overlap. A block may be empty
(nr
and/or nc
equal to 0, and corresponding arow*
and
acol*
values set to NA.) id
must not contain semicolons.
Columns arow1
, arow2
, acol1
and acol2
refer to
row and column numbers in the augmented row-column grid of the table; see
adim
for more information.
In addition to the required columns listed above, x
should contain
any other columns that will be used by a blockStyle
to add
graphical properties to blocks. These should be listed in the
match_columns
attribute of the style.
If x
is already a tblBlocks
object, this function does some
validity checks. If x
is NULL, a valid but empty tblBlocks
object is returned.
Value
An S3 object of class tblBlocks
. It is just the data frame
x
with the additional class tblBlocks
(after checking that
x
contains the necessary columns), and attribute
rowgroupSize
. The latter is copied from x
if present and
set to NA if not.
See Also
Promote a Data Frame to a tblentries
Object
Description
Promote a data frame to a tblEntries
object. This is an internal
function not intended to be called by package users.
Usage
as.tblEntries(x)
Arguments
x |
An object inheriting from |
Details
Normally table entries are created from a textTable
object via
function tblEntries
. This function allows them to be created or
edited directly in a data frame.
Columns arow1
, arow2
, acol1
and acol2
refer to
row and column numbers in the augmented row-column grid of the table; see
adim
for more information.
If x
is already a tblEntries
object, this function does some
validity checks. If x
is NULL, a valid but empty tblEntries
object is returned.
Value
An object of S3 class tblEntries
and data.frame
.
See Also
Extract the prblocks
Object from a Plot-Ready or Plotted Table
Description
Extract the prBlocks
object from a plot-ready or plotted table.
This is an internal function, not intended to be called by package users.
Usage
blocks(x, enabledOnly=TRUE)
Arguments
x |
A plot-ready ( |
enabledOnly |
Logical. If TRUE, only the subset of table blocks that are enabled is extracted. |
Value
A prBlocks
object, containing blocks for a table, or NULL if none
have been defined.
Update the Blocks of a Plot-Ready or Plotted Table
Description
Update the blocks component of a plot-ready (prTable
) or plotted
(pltdTable
) table object. This is an internal function, not
intended to be called by package users.
Usage
blocks(x) <- value
Arguments
x |
A plot-ready ( |
value |
A |
Value
An object like x
, with updated hvrules.
Constrained Display Sizes of Each Table Row, Column and Entry
Description
Calculate the display widths (in mm) of each table column, heights of each
table row, and horizontal and vertical dimensions of each table entry.
Calculations may use the constraints imposed by minwidth
and
maxwidth
for each entry. This is an internal utility function, not
intended to be called by package users.
Usage
calc_rcsize(entryInfo, vrule_hsize, hrule_vsize, sizeAdjust,
nominal_rcmin, method)
Arguments
entryInfo |
A |
vrule_hsize |
Numeric vector with length (# table columns) + 1, giving the horizontal dimensions, in mm, of vertical rules in the table. |
hrule_vsize |
Numeric vector with length (# table rows) + 1, giving the vertical dimensions, in mm, of horizontal rules in the table. |
sizeAdjust |
Two-element numeric vector containing multipliers to adjust the calculated absolute size of table text, when determining row and column sizes. Essentially fudge factors. The first element is applied to the horizontal dimension and the second to the vertical dimension. |
nominal_rcmin |
A nominal minimum size for any row or column, in mm. It is used to avoid
division by 0 when calculating the proportional change in size due to
constraints, when |
method |
Which algorithm/objective function is used for the constrained optimization problem.
|
Details
Entries can span multiple columns and rows, and can have constraints on
their minimum and maximum widths. This function calculates row and column
dimensions that satisfy the constraints while minimizing an objective
function that measures deviations from their natural sizes. They are the
solution to a quadratic programming problem. An error will be raised if
the QP has no solution (e.g., if minwidth
and maxwidth
collectively, over all entries, are inconsistent).
minwidth
and maxwidth
are in the text's frame of reference,
and may be expressed in two forms. Positive values are interpreted as
absolute widths in millimeters, and *should* include the amount of any
padding specified by hpad
(when angle
is 0 or 180 degrees)
or vpad
(when angle
is 90 or 270 degrees), as well as
scaling by sizeAdjust
. Negative values are interpreted as
multiples of the natural text width without wrapping and *without*
including padding or sizeAdjust
. Thus setting minwidth
for
an entry to -1 will guarantee that the width of the spanned cell(s) will
be at least enough to contain it without wrapping.
An NA value for
minwidth
means there is no constraint on minimum width, and is equivalent to 0. AnInf
value formaxwidth
means there is no constraint on maximum width. In the absence of constraints, the internal algorithm favors widths as close as possible to the natural width of the entry text, without wrapping.An NA value for
maxwidth
means the maximum width will be determined passively from themaxwidth
values of other entries in the same table column(s) (ifangle
is 0 or 180) or row(s) (ifangle
is 90 or 270). (It will never be less thanminwidth
.) This may be useful for table titles and footnotes, where long text should be wrapped to fit widths implied by the other table entries.Setting
maxwidth
to NA or to a finite value> -1
and< Inf
means the spanned cell(s) may not be wide enough to hold the text without wrapping it into multiple lines.The general effect of setting
minwidth
to a non-zero value is to reduce or prevent text wrapping, while the general effect of settingmaxwidth
to NA or a finite value is to encourage wrapping. Settings for one entry may affect the width and wrapping of other entries, because column widths and row heights for the table as a whole must satisfy the constraints for all their entries.Text representing
plotmath
expressions cannot be wrapped, somaxwidth
should beInf
or<= -1
for such entries.
method=0
ignores minwidth
and maxwidth
when
determining row and column sizes. However a warning will be raised if the
resulting sizes violate the constraints for any enabled entries.
Value
List with components:
hsizeCol |
Numeric vector of display widths for each table column, in mm. |
vsizeRow |
Numeric vector of display heights for each table row, in mm. |
sizeInfo |
Data frame with one row per table entry. Columns are |
Note
Operation of this function is controlled by parameters in internal object
internalOpt
, specifically those with prefix rcsize_
. Values
of option rcsize_verbose
greater than 2 will cause a data frame of
calculated entry widths to be written to the global environment for each
iteration.
Among methods 2-5, 2 and 4 seem best because they do not alter the target
size in the numerator; method 5 encourages expanding row *and* column
sizes by rcsize_rcmin
even when no wrapping is required in a given
direction.
See Also
entrySize_mm
, called by this function to calculate the sizes
in sizeInfo
.
Calculate X, y Positions and H|vjust Values for Entries
Description
Calculate coordinates and h|vjust values for entry text strings, to achieve the desired justification and alignment with respect to cell boundaries. This is an internal utility function, not intended to be called by package users.
Usage
coord_justif(df, x0, x1, y0, y1, size, align=df$align)
Arguments
df |
Data frame with one row per entry. Required columns are |
x0 , x1 , y0 , y1 |
Numeric vectors with one element per entry, giving the coordinates (in mm) of the boundaries of the cell(s) containing each entry. Note that the origin is at the top left of the table. |
size |
Data frame with one row per entry, and columns |
align |
Optional numeric vector with one element per entry. It specifies
horizontal alignment of multiple lines within an entry *with respect to
each other*. 0 means all lines in the entry are aligned at their left
edge ("left justified"), 1 means they are all aligned at their right edge
("right justified"), 0.5 means they are aligned at their centers. The
default is to use column |
Details
The need to jointly calculate x
, y
, gg_hjust
, and
gg_vjust
is due to a difference between tablesgg
and
ggplot2
in their interpretations of text justification.
ggplot2
interprets justification parameters as indicating position
of text relative to the (x,y) coordinates used to draw the text: 0 means
to the right/above (x,y), 1 means to the left/below (x,y).
tablesgg
interprets justification parameters as position relative
to the boundaries of the table cell(s) containing the entry text: 0 means
at the left/top boundary, 1 means at the right/bottom boundary.
This function takes cell boundary coordinates x0
, x1
,
y0
, y1
and tablesgg
-type justification parameters and
converts them to the ggplot2
-type (x,y) coordinates and
justification parameters. In doing so it is also necessary to take any
text rotation (specified by graphical property angle
) into account.
Values provided to geom_*
functions should be x
, y
,
hjust=gg_hjust
, and vjust=gg_vjust
. If the geom_*
function has an halign
argument (e.g., for geom_textbox
),
set it to gg_hjust
.
Justification values in [0, 1] will never position text closer to cell
boundaries than the padding specified by df$hpad
and
df$vpad
.
Value
Data frame with one row per row of df
. Columns are:
x , y |
Coordinates to give to a |
gg_hjust , gg_vjust |
|
See Also
Specifications for Fields Used in Certain Object Classes
Description
Return a data frame with specifications for descriptor and graphical property fields required for certain object classes used within the package. This is an internal function, not intended to be called by package users.
Usage
dfSpecs(objClass)
Arguments
objClass |
One of |
Details
Descriptor and graphical property fields are documented in
?elements
.
Value
A data frame with one row per descriptor or graphical property field.
Columns are name
(the name of the field); mode
(mode/type of
values taken by the field); and NA_ok
(logical, TRUE if NA is a
valid value for the field).
Field names are used as the row names of the data frame.
See Also
df_from_spec
, which uses the output from this function to
create a template data frame containing the required fields;
grSpecs
, which returns specifications for the graphical
properties for each element type.
Create a Data Frame from a Specification
Description
Create a data frame from a specification that describes its column names and modes. All entries are NA (of the appropriate mode). This is an internal function, not intended to be called by package users.
Usage
df_from_spec(x, n)
Arguments
x |
A data frame with (at least) columns |
n |
The number of rows desired for the returned data frame. May be 0. |
Value
A data frame with as many columns as x
has rows. Column names are
taken from x$name
and modes from x$mode
. (See
?mode
).
Specify Visual Properties for Table Blocks
Description
Specify a set of graphical properties that can be used to highlight a rectangular block of table cells.
Usage
element_block(fill=NULL, fill_alpha=NULL, border_size=NULL,
border_colour=NULL, border_color=NULL, enabled=NULL,
inherit.blank=FALSE)
Arguments
fill , fill_alpha , border_size , border_color |
Scalar graphical properties for the table blocks. These will be passed to
|
border_colour |
Alias for |
enabled |
Logical scalar, controlling whether the block is displayed (TRUE) or not (FALSE). |
inherit.blank |
Ignored. |
Details
This function is modeled on the element_*
functions used in
ggplot2
to specify graphical properties in themes. It is primarily
used to create the value on the right-hand side of an assignment involving
the props<-
group of setter functions.
To display a table block means to highlight its rectangular region with
shading (as specified by fill
, a color, and fill_alpha
)
and/or a border (with thickness specified by border_size
, in mm,
and color border_color
). Blocks are drawn before entries and
hvrules, so the latter are drawn "on top" of blocks and will not be
hidden.
Quantitative property border_size
may be specified using the
ggplot2
function rel()
. This function indicates that the
value is to be interpreted as a multiplier to be applied to whatever the
current value of the property is. For example border_size=rel(1.2)
specifies that the thickness of the border around a block is to be
increased by 20% from its current value.
Value
An object of S3 classes element_block
and element
.
See Also
element_entry
, element_hvrule
;
elements
for more detail about the available graphical
properties; props<-
, propsa<-
,
propsd<-
.
Examples
plt <- plot(iris2_tab, title="Summary statistics for the iris data")
props(plt, id="rowhead") <- element_block(fill="lightblue")
props(plt, id="colblock/C/2/1") <- element_block(border_color="red")
# (Default fill color for blocks is 'gray85')
plt
Specify Visual Properties for Table Entries and their Cells
Description
Specify a set of graphical properties that can be used to display table entries and the cells that contain them.
Usage
element_entry(text=NULL, family=NULL, fontface=NULL, colour=NULL,
alpha=NULL, size=NULL, hjust=NULL, vjust=NULL, angle=NULL,
lineheight=NULL, color=NULL, hpad=NULL, vpad=NULL, fill=NULL,
fill_alpha=NULL, border_size=NULL, border_colour=NULL,
border_color=NULL, minwidth=NULL, maxwidth=NULL, enabled=NULL,
textspec=NULL, inherit.blank=FALSE)
Arguments
text |
Scalar character string, the text to be displayed for the entries. |
family , fontface , color , alpha , size , hjust , vjust , angle , lineheight |
Scalar values for the graphical properties that are used to display the
text of table entries. Values will be passed to
|
hpad , vpad |
Amount of blank space to add on the left and right ( |
fill , fill_alpha , border_size , border_color |
Scalar graphical properties for the _cells_ that contain table entries.
These will be passed to |
colour , border_colour |
Aliases for |
minwidth , maxwidth |
Minimum, maximum width for cell(s) spanned by an entry. Positive values
represent absolute sizes in millimeters, and should include any padding.
Negative values are interpreted as multiples of the natural width of the
entry text, without padding. Use values of |
enabled |
Logical scalar, controlling whether the entry is displayed (TRUE) or not (FALSE). This applies to both the entry text and the cells that contain it. |
textspec |
Character string indicating any special features of the text in
|
inherit.blank |
Ignored. |
Details
This function is modeled on the element_*
functions used in
ggplot2
to specify graphical properties in themes. It is primarily
used to create the value on the right-hand side of an assignment involving
the props<-
group of setter functions.
The text content of an entry is perhaps not strictly a graphical property, but it is convenient to have an easy way to modify it. Note that like all other properties, the provided value must be a single value (character string), not a longer vector of values.
Justification of text within a cell is specified by properties
hjust
and vjust
. Their interpretation is with respect to
the boundaries of the cell: 0 means justification toward the left/top of
the cell, 1 means toward the right/bottom, and 0.5 means centered. This
is different from the interpretation in ?ggplot2::geom_text
, where
the justification is with respect to an (x, y) point. Note that padding
(hpad
, vpad
) is added _after_ justification, so for example
hjust=0
will put the text at a distance hpad
from the left
border of its cell.
Quantitative properties (size
, lineheight
, hpad
, etc)
may be specified using the ggplot2
function rel()
. This
function indicates that the value is to be interpreted as a multiplier to
be applied to whatever the current value of the property is. For example
lineheight=rel(1.2)
specifies that the lineheight property of an
entry is to be increased by 20% from its current value.
Value
An object of S3 classes element_entry
and element
.
See Also
element_hvrule
, element_block
,
element_refmark
; elements
for more detail
about the available graphical properties; props<-
,
propsa<-
, propsd<-
.
Examples
plt <- plot(iris2_tab, title="Summary statistics for the iris data",
subtitle="Shown with default graphical properties")
plt
props(plt, id="body") <- element_entry(fontface=3, fill="gray")
props(plt, id="subtitle,1") <-
element_entry(text="Entry properties changed by 'props<-'",
fill="gray", color="red")
plt
Specify Visual Properties for Table Rules
Description
Specify a set of graphical properties that can be used to display horizontal or vertical rules (hvrules) in a table.
Usage
element_hvrule(colour=NULL, alpha=NULL, linetype=NULL, size=NULL,
fill=NULL, fill_alpha=NULL, space=NULL, color=NULL, enabled=NULL,
inherit.blank=FALSE)
Arguments
color , alpha , linetype , size |
Scalar values for the graphical properties that are used to display the
horizontal or vertical line of an hvrule. Values will be passed to
|
fill , fill_alpha , space |
Scalar values for the graphical properties of the (long, thin) rectangle
that encloses an hvrule. |
colour |
Alias for |
enabled |
Logical scalar, controlling whether the hvrule is displayed (TRUE) or not (FALSE). This applies to both the actual rule (line) and the rectangle containing it. |
inherit.blank |
Ignored. |
Details
This function is modeled on the element_*
functions used in
ggplot2
to specify graphical properties in themes. It is primarily
used to create the value on the right-hand side of an assignment involving
the props<-
group of setter functions.
A horizontal or vertical rule (hvrule) is actually drawn as long, narrow
rectangle, with a line centered inside it. The narrowness of the
rectangle, and thus how much space the hvrule adds to the table, is
controlled by space
. The thickness of the line inside the
rectangle is controlled by size
. Setting linetype
to 0
means no line will be drawn, but the enclosing rectangle will be. In that
way hvrules can be used to insert extra blank space between rows or
columns of a table.
Quantitative properties size
and space
may be specified
using the ggplot2
function rel()
. This function indicates
that the value is to be interpreted as a multiplier to be applied to
whatever the current value of the property is. For example
space=rel(1.2)
specifies that the space
property of an entry
is to be increased by 20% from its current value.
Value
An object of S3 classes element_hvrule
and element
.
See Also
element_entry
, element_block
;
elements
for more detail about the available graphical
properties; props<-
, propsa<-
,
propsd<-
.
Examples
plt <- plot(iris2_tab, title="Summary statistics for the iris data")
plt
# Enable the vertical rule between rowhead and body, and set its
# properties:
props(plt, id="rowhead_right") <- element_hvrule(enabled=TRUE, linetype=1,
color="black", space=10)
plt
# Change the properties of all enabled hvrules:
propsd(plt, subset=(enabled)) <- element_hvrule(color="red")
plt
Specify a Reference Mark that can be Added to Table Entries
Description
Specify a reference mark (a symbol placed before or after entry text to indicate cross-references; e.g. for footnotes) that can be added to entries in a table.
Usage
element_refmark(mark=NULL, side=NULL, raise, ..., inherit.blank=FALSE)
Arguments
mark |
Character string containing the character(s) to be used as the reference mark. |
side |
Character string indicating where the reference mark is to be placed: "before" or "after" the entry text. |
raise |
Logical scalar. If TRUE, the reference mark will be displayed as a
superscript, using |
... |
Additional arguments passed to |
inherit.blank |
Ignored. |
Details
This function is modeled on the element_*
functions used in
ggplot2
to specify graphical properties in themes. It is primarily
used to create the value on the right-hand side of an assignment involving
the props<-
group of setter functions.
Value
An object of S3 classes element_refmark
and element
. If any
arguments are specified in ...
, they are passed to
element_entry
and the resulting object is attached as attribute
extra
.
See Also
addRefmark
for a different way to add reference marks, and
for more information about reference marks in general.
element_entry
, props<-
,
propsa<-
, propsd<-
.
Examples
plt <- plot(iris2_tab, title="Summary statistics for the iris data",
foot="sd = standard deviation")
props(plt, id="foot") <- element_refmark(mark="*", side="before")
# Add a reference mark to just the first appearance of 'sd' in the row header:
propsa(plt, arows=arow(plt, hpath=c("setosa", "sd")), acols=2) <-
element_refmark(mark="*", side="after")
plt
Extract Table Elements from a Plotted Table
Description
Extract table elements (entries, blocks, or hvrules) from a plotted table, as a simple data frame with one row per element.
Usage
elements(x, type=c("entry", "block", "hvrule"), enabledOnly=TRUE)
Arguments
x |
A |
type |
Character scalar indicating the type of elements to extract: one of "entry", "block", or "hvrule". |
enabledOnly |
Logical scalar. If TRUE, only elements that are currently enabled in
|
Details
A plotted table (pltdTable
object) has three types of elements:
entries, blocks, and hvrules. Entries are the text strings (and
associated properties) displayed in table cells. Blocks are
rectangular sets of contiguous table cells. And hvrules are
spacers, with or without a visible line (or "rule"), used to separate or
group table rows and columns. See the package vignette for more
information.
This function allows one to inspect these elements. The purpose is
primarily informational: an easy way to view all the elements of a table,
their descriptors (e.g., as used by styles and the propsd<-
function), and the graphical properties they have been assigned. It is
not intended as a way to edit or modify elements. For that, see
update
methods for textTable
and pltdTable
objects,
the props<-
set of functions, and section 4 of the package
vignette.
The remainder of this section describes the columns in the returned data frame, for each element type.
Columns in elements(x, type="entry")
Entry descriptors:
- id
Character string that uniquely identifies the entry. The format is
<part>,<partrow>,<partcol>
for table parts that are matrices (rowhead
,rowheadLabels
,colhead
, andbody
), and<part>,<partrow>
for table parts that are vectors (annotation partstitle
,subtitle
, andfoot
).- part
Character string identifying the part of the table to which the entry belongs: one of "body", "rowhead", "colhead", "rowheadLabels", "title", "subtitle", or "foot".
- subpart
Character string with further information about the nature of of the entry within its part of the table. May be NA.
- partrow, partcol
Row number, column number of the entry within its table part. For parts that are vectors rather than matrices,
partrow
will be the element number within the vector, andpartcol
will be NA. If an entry spans more than one row or column, the minimum row/column number of the spanned cells is used.- headlayer
How far (in number of rows or columns) from the body of the table the entry is. By definition this is 0 for entries in the body of the table. It is 1 for row/column headers immediately adjacent to the body, 2 for headers one row/column further out, and so on. The layer numbers for row header labels match those for the corresponding columns of row headers. The layers for titles, subtitles, and foot lines are the number of _rows_ from the body of the table. When a table is created with
rowheadInside
set to TRUE, theheadlayer
value for the outermost layer of row headers (and for its label, if any) is changed to 0, since the headers become interleaved with the table body.- level_in_layer
Numbering of entries within a given part and headlayer. For row and column headers this is based their hierarchical structure (see the descriptors for blocks, below). For other table parts it is just an integer from 1 to the number of entries in that layer of that part.
- multirow, multicolumn
Logicals indicating whether the entry spans multiple rows or columns of the table.
- text
Character string containing the formatted content of the entry, for display. It may use
plotmath
notation for mathematical notation, or markdown/HTML tags; seetextspec
below.- type
Character string identifying the type of value the entry represents (e.g., "numeric"). May be NA. The default for table annotation (
title
,subtitle
,foot
) androwheadLabels
is "character".- textspec
Character string indicating any special features of the text in
text
. Currently supported values are "plain", "plotmath", and "markdown". "plotmath" indicates that the entry text contains mathematical notation as described in?plotmath
. "markdown" means the text may contain markdown or HTML tags to control its appearance; this requires theggtext
package.- enabled
Logical indicating whether the entry is to be displayed when the table is plotted. If FALSE the entry is ignored when laying out the table or determining its size.
- arow1, arow2, acol1, acol2
Range of row and column numbers occupied by an entry, with respect to the augmented row-column grid for the table.
arow1
<arow2
and/oracol1
<acol2
means the entry spans multiple rows and/or columns.
Graphical properties for entries. Values for these are assigned by
a style, either a default style (see ?tablesggOpt
) or
user-specified.
- hjust
Numeric horizontal justification for entry text (0=left, 0.5=center, 1=right).
- vjust
Numeric vertical justification for entry text (0=top, 0.5=center, 1=bottom).
- color
Character string; color for entry text.
- alpha
Numeric value in [0, 1] specifying transparency of entry text (0=transparent, 1=opaque).
- size
Font size for entry text, in points (72.27 points = 1 inch, 2.845 points = 1 mm).
- family
Character string, the font to use for entry text. "serif", "sans", and "mono" will work for all graphics devices. Other fonts may or may not be available on a particular device.
- fontface
Numeric indicating 1=plain, 2=bold, 3=italic, 4=bold and italic.
- lineheight
Numeric multiplier that adjusts interline spacing for multi-line entry text. 1.0 gives the default spacing.
- angle
Rotation angle for entry text, in degrees counter-clockwise from horizontal.
- hpad, vpad
Padding added around the sides of entry text to keep it from touching cell borders, in millimeters.
hpad
is added on both the left and right sides of the text, andvpad
is added on both the top and bottom.- fill
Character string; background color for the cell(s) containing the entry. NA means no background color.
- fill_alpha
Numeric value in [0, 1] specifying transparency of the cell background color (0=transparent, 1=opaque).
- border_size
Thickness of the border to draw around the cell(s) containing the entry text, in millimeters.
- border_color
Character string; color for the border around entry text. NA means no border.
- minwidth, maxwidth
Minimum and maximum width for the cell(s) spanned by the entry. (Here width is with respect to the text itself; i.e., the direction of reading for English text, and therefore measured vertically if the text is rotated by 90 or 270 degrees.) They may be expressed in two forms. Positive values are interpreted as absolute widths in millimeters, and should include the amount of padding specified by
hpad
(whenangle
is 0 or 180 degrees) orvpad
(whenangle
is 90 or 270 degrees). Negative values are interpreted as multiples of the natural width of the text itself, without including padding. Thus settingminwidth
for an entry to-1
will guarantee that the width of the spanned cell(s) will be at least enough to contain the text without wrapping.An NA value for
minwidth
means there is no constraint on minimum width, and is equivalent to 0. AnInf
value formaxwidth
means there is no constraint on maximum width. (However in the absence of constraints, the internal algorithm favors widths as close as possible to the natural width of the entry text, without wrapping.)An NA value for
maxwidth
means the maximum width will be determined passively from themaxwidth
values of other entries in the same table column(s) (ifangle
is 0 or 180) or row(s) (ifangle
is 90 or 270). (It will never be less thanminwidth
.) This may be useful for table titles and footnotes, where long text should be wrapped to fit widths implied by the other table entries.Setting
maxwidth
to NA or to a finite value> -1
and< Inf
means the spanned cell(s) may not be wide enough to hold the text without wrapping it into multiple lines. Therefore optiontablesggOpt("allowWrap")
must be TRUE, and a warning will be raised andmaxwidth
will be ignored if not.The general effect of setting
minwidth
to a non-zero value is to reduce or prevent text wrapping, while the general effect of settingmaxwidth
to NA or a finite value is to encourage wrapping. Settings for one entry may affect the width and wrapping of other entries, because column widths and row heights for the table as a whole must satisfy the constraints for all their entries.Text representing
plotmath
expressions cannot be wrapped, somaxwidth
should beInf
or<= -1
for such entries.
Columns in elements(x, type="block")
Block descriptors:
- id
Character string that uniquely identifies the block. The format is just
<type>
for blocks types that are unique. For blocks associated with row or column headers, or with row groups formed by the plot optionrowgroupSize
, ID's begin with<type>/<subtype>/<headlayer>/<level_in_layer>
. See Appendix B of the package vignette for details about the definitions and ID's of these blocks.- type
Character string that specifies the nature or structural role of the block. One of
- "table"
The whole table (all cells).
- "title", "subtitle", "colhead", "rowhead", "rowheadLabels", "body", "foot"
The standard table parts. (If there are interior row header entries, "rowhead" and "body" are omitted because the interleaving of headers and body means neither are valid blocks.)
- "titles"
The union of the
title
andsubtitle
parts.- "stub"
If we exclude the title/subtitle and foot annotations, a table has four quadrants: the body at the lower right, the row headers at the lower left, the column headers at the upper right, and a stub at the upper left. That is, the stub consists of the cells above the row headers and to the left of the column headers. (If there are row header labels–block "rowheadLabels"–they will be in the bottom row of the stub.)
- "colhead_and_stub", "rowhead_and_stub"
The unions of "stub" with "colhead" and "rowhead", respectively.
- "colhead_and_body", "rowhead_and_body"
The unions of "body" with "colhead" and "rowhead", respectively.
- "rowblock", "colblock"
Collections of blocks associated with row and column headers, reflecting their hierarchical structure. "rowblock" is also the type for blocks representing row groups formed by plot option
rowgroupSize
. See Appendix B of the package vignette for details.
- subtype
Character string refining block type. For types "rowblock" and "colblock", subtypes are "A", "B", "C", and (for "rowblock" only) "G". See Appendix B of the package vignette for their meaning. For other block types the subtype is set to missing (NA).
- headlayer
For "rowblock" and "colblock" blocks, the header layer number with which the block is associated. (Layer numbers increase from innermost to outermost layer.) For other block types,
headlayer
is NA.- level_in_layer
For "rowblock" and "colblock" blocks, the level number (within the header layer) with which the block is associated. Levels are numbered from 1 to the maximum number of levels in that layer. For other block types,
level_in_layer
is NA.- group_in_level
For "rowblock" blocks of subtype "G" (representing sets of rows grouped according to
rowgroupSize
), the group number within a header layer and level. NA for other block types/subtypes.- had_enabled_entries
Logical, set to TRUE if there were _enabled_ table entries in
x
that intersect the block. This is set at the time the plotted table (pltdTable
object) is created. It is not updated if entries are later enabled/disabled usingprops<-
, for example.- nr, nc
The number of rows and columns, respectively, that the block spans. May be 0 for empty blocks.
- arow1, arow2, acol1, acol2
First and last row and column numbers spanned by the block, with respect to the augmented row-column grid for the table. Empty blocks, with no rows or no columns (
nr
ornc
equal to 0), will have the correspondingarow*
oracol*
set to NA.- enabled
Logical indicating whether the block is to be displayed when the table is plotted. This applies only to highlighting the rectangular region occupied by the block using a fill color or border. It has no effect on display of entries or hvrules contained within the block.
Graphical properties for blocks. Values for these are assigned by
a style, either a default style (see ?tablesggOpt
) or
user-specified.
- fill
Character string; color used to fill the rectangular region contained in the block. NA means the region is not colored. (Blocks are drawn before table entries or hvrules, so the block fill color will not hide those elements even if it is opaque.)
- fill_alpha
Numeric value in [0, 1] specifying transparency of the block fill color (0=transparent, 1=opaque).
- border_size
Thickness of the border to draw around the block, in millimeters.
- border_color
Character string; color for the border around the block. NA means no border.
Columns in elements(x, type="hvrules")
hvrule descriptors:
- id
Character string that uniquely identifies the hvrule. The format is
<block>_<side>
.- direction
Character string, either "hrule" for a horizontal rule or "vrule" for a vertical rule.
- block
The ID of the block along the side of which the hvrule runs.
- side
Which side of the block the hvrule runs along, "top", "bottom", "left", or "right".
- adjacent_blocks
Character string containing the IDs of blocks that are adjacent to
block
on the same side as the hvrule. (I.e., blocks that are separated fromblock
by the hvrule.) Block IDs within the string are separated by semicolons. If there are no adjacent blocks the string will be empty ("").- arow1, arow2, acol1, acol2
Location of the hvrule with respect to the augmented row-column grid of the table. An hrule is inserted between table rows, and therefore
arow1
andarow2
are the same and equal to a half-integer. For example, an hrule inserted between rows 3 and 4 hasarow1 = arow2 = 3.5
.acol1
andacol2
for the hrule are integers indicating the range of columns that it spans. Analogously, a vrule is inserted between table columns, soacol1
andacol2
are identical and equal to a half-integer, whilearow1
andarow2
are integers that indicate the range of rows spanned by the vrule.- enabled
Logical indicating whether the hvrule is to be displayed when the table is plotted. If FALSE the hvrule is ignored when laying out the table or determining its size.
Graphical properties for hvrules. Values for these are assigned by
a style, either a default style (see ?tablesggOpt
) or
user-specified.
- linetype
Integer indicating the type of line to display. 1 = solid line; 2 = dashed; 3 = dotted. (See the documentation of
lty
in?par
for the full set of choices.) A line type of 0 means no line will be drawn, so the hvrule just inserts empty space between table rows or columns.- size
Thickness of the line, in millimeters.
- color
Character string; the color of the line.
- alpha
Numeric value in [0, 1] specifying transparency of the line color (0=transparent, 1=opaque).
- space
The width (for a vertical rule) or height (for a horizontal rule) of the rectangle inserted between columns or rows by the hvrule. (A line, if any, is drawn within this rectangle.) This is the amount of space the rule adds to the width or height of the table, in millimeters.
- fill
Character string; color used to fill the rectangle containing the hvrule. NA means the region is not colored.
- fill_alpha
Numeric value in [0, 1] specifying transparency of the fill color (0=transparent, 1=opaque).
Value
A data frame with one row per element. Columns include element descriptors and graphical properties assigned to each element. The row names of the data frame will be the element ID's.
See Also
Examples
plt <- plot(iris2_tab)
str(elements(plt, type="entry"))
str(elements(plt, type="block")) # 0 rows, none are enabled for display
str(elements(plt, type="block", enabledOnly=FALSE))
str(elements(plt, type="hvrule"))
Extract the prentries
Object from a Plot-Ready or Plotted Table
Description
Extract the prEntries
object from a plot-ready or plotted table.
This is an internal function, not intended to be called by package users.
Usage
entries(x, enabledOnly=TRUE)
Arguments
x |
A plot-ready ( |
enabledOnly |
Logical. If TRUE, only the subset of table entries that are enabled is extracted. |
Value
A prEntries
object, containing plot-ready entries for a table.
Update the Table Entries of a Plot-Ready or Plotted Table
Description
Update the table entries component of a plot-ready (prTable
) or
plotted (pltdTable
) table object. This is an internal function,
not intended to be called by package users.
Usage
entries(x) <- value
Arguments
x |
A plot-ready ( |
value |
A |
Value
An object like x
, with updated table entries.
Find the Entries that are Contained Within a Set of Table Blocks
Description
For each table block, find the entries that are completely or partially contained within it. This is an internal utility function, not intended to be called by package users.
Usage
entries_by_block(x, blocks, strict)
Arguments
x |
An object containing table entries, such as |
blocks |
A |
strict |
Logical scalar. If TRUE, only entries completely contained with a given block are included. If FALSE, entries that overlap the block but are not completely contained within it will also be included. |
Value
A list with one component per block in blocks
. Component i
contains a numeric vector with the indices of the entries in x
that
belong to block i
.
Calculate the Sizes of Table Entries, in Mm
Description
Calculate the horizontal and vertical sizes, in millimeters, of the text
strings in a prEntries
object. This is an internal function, not
intended to be called by package users.
Usage
entrySize_mm(entryInfo, allowWrap, sizeAdjust=c(1, 1))
Arguments
entryInfo |
A |
allowWrap |
Logical scalar. If TRUE, entry sizes will be calculated after any text
wrapping required by |
sizeAdjust |
Two-element numeric vector containing multipliers to adjust the calculated
absolute size of table text. The first element is applied to the
horizontal dimension and the second to the vertical dimension. Ignored if
|
Details
The dimensions are for an unrotated rectangle that just encloses the
(possibly rotated) text. (So hsize
is always measured parallel to
the x-axis and vsize
parallel to the y-axis; i.e., they are with
respect to the reference frame of the whole table.)
This relies on the functions grid::convertWidth
and
grid::convertHeight
. They require that a graphics device to be
open. It would be natural to use the currently active device, if any, but
this seems to generate empty pages on that device. Therefore a temporary
PDF device is silently opened, and then deleted at the end.
String sizes may vary slightly between different graphics devices, even with the same graphics properties (font size, family, face, etc).
The height of text processed with richtext_grob
or
textbox_grob
differs from the same text processed with
textGrob
: (a) The former includes the height of character
descenders (whether or not the text actually includes characters with
descenders), whereas the latter does not. (b) Interline spacing seems to
be smaller with the former than with the latter. Descender height is
returned in column descender
; it will be 0 for text not processed
with richtext_grob
or textbox_grob
.
Value
Data frame with the same row names as entryInfo
, and columns:
hsize
and vsize
containing entry dimensions in millimeters;
horiz
(logical, TRUE if entry angle is 0 or 180 degrees);
descender
(amount of space included in hsize
(if
horiz
is FALSE) or vsize
(if horiz
if TRUE) to allow
for descenders); and wrap
(logical, whether text
needed to
be wrapped to satisfy maxwidth
).
The data frame has an attribute device
, containing the name of the
graphics device used when calculating text sizes. (Currently this is
always "pdf".)
See Also
Evaluate a Set of Logical Conditions Within a Data Frame
Description
Evaluate each of a set of logical conditions
within a data frame
x
. This is an internal utility function, not intended to be called
directly by package users.
Usage
eval_conditions(x, conditions, NA_condition_value=TRUE)
Arguments
x |
A data frame. |
conditions |
Character vector. Each element should represent an expression that can be
evaluated within |
NA_condition_value |
Logical scalar, TRUE, FALSE, or NA. The value to use in place of
evaluation when an element of |
Details
Each condition should generally represent an expression involving columns
of x
. It is evaluated using x
as the environment, and must
return either a logical vector with length equal to the number of rows in
x
, or a logical scalar (which will be replicated into a vector of
the right length). The resulting vectors, one per condition, form the
columns of the returned matrix.
A condition may be NA or the empty string. In that case it is not
evaluated, and a vector containing NA_condition_value
is used
instead.
Value
Logical matrix with one row for each row of x
and one column for
each condition in conditions
. Element [i, j]
contains the
result of evaluating condition[j]
for the i
-th row of
x
.
Indices to Impute NA Elements of a Vector by LOCF
Description
Indices to impute NA elements of a vector by the last-observation-carried-forward method. This is an internal function, not intended to be called by package users.
Usage
fill_NA_idx(y)
Arguments
y |
A vector. |
Value
A vector of indices with the same length as y
. If x <-
y[fill_NA_idx(y)]
, then x
will be y
with NA values imputed
by the last-observation-carried-forward method.
Format Entries in an xtable
into Character Strings
Description
Format entries in an xtable
object into character strings. (This
is essentially a format
method for xtable
objects.) This is
an internal function not intended to be called by package users.
Usage
format_xtable(x, row.names=TRUE, na="NA", mathExponents=TRUE, ...)
Arguments
x |
An |
row.names |
Logical scalar. If FALSE, the row names of |
na |
String to be used to represent missing values in |
mathExponents |
Logical scalar. If TRUE, then numerical values in |
... |
Additional named arguments passed to |
Details
This is mostly code extracted from print.xtable
in version 1.8-4 of
the xtable
package by David B. Dahl et al.
Value
A character matrix with one row per row in x
(not counting column
names), and one column per column in x
(including a column of row
names, if row.names
is TRUE).
Specifications for Graphical Properties for an Element Type
Description
Return a data frame with specifications for graphical properties associated with an element type. This is an internal function, not intended to be called by package users.
Usage
grSpecs(type)
Arguments
type |
Element type, one of |
Details
Graphical properties are documented in ?elements
.
Value
A data frame with one row per graphical property. Columns are name
(the name of the property); mode
(mode/type of values taken by the
property); NA_ok
(logical, TRUE if NA is a valid value for the
property); and scalable
(logical, TRUE if the property is to be
treated as scalable).
Property names are used as the row names of the data frame.
See Also
df_from_spec
, which uses the output from this function to
create a template data frame for graphical properties.
Runs of Repeated Values in a Header Matrix
Description
Identify runs of repeated values in a matrix of row or columns headers. Detection of runs respects the hierarchical structure of headers. This is an internal utility function, not intended to be called by package users.
Usage
headerRuns(x, which_head)
Arguments
x |
A matrix containing table row or column headers. |
which_head |
Character scalar, "row" or "col", indicating whether |
Details
Runs are defined cumulatively across header variables. For the outermost
variable, runs consist of consecutive duplicated values in the first
column/row of x
; for the second-outermost variable, runs are
defined by consecutive duplicated values in the first two columns/rows of
x
, and so on. (That is, the header variables are treated as a
hierarchy, with inner variables nested within outer ones.)
Value
A list with one component per header variable in x
. Each component
is a data frame. The i
-th data frame has one row per run of values
in the i
-th header variable, with columns:
headlayer |
Header layer number, increasing from innermost (most deeply nested) to
outermost. Thus for "row" headers it is the reverse of column number in
|
level_in_layer |
Run number within the layer. Levels are numbered from 1, so this column is just the sequence from 1 to the number of rows in the data frame. |
value |
The value in |
start |
Position in |
runlen |
Length of the run (number of rows or columns). |
If x
is NULL, the returned value is also NULL. If x
has no
header variables, the returned value is an empty list, list()
.
Extract the prhvrules
Object from a Plot-Ready or Plotted Table
Description
Extract the prHvrules
object from a plot-ready or plotted table.
This is an internal function, not intended to be called by package users.
Usage
hvrules(x, enabledOnly=TRUE)
Arguments
x |
A plot-ready ( |
enabledOnly |
Logical. If TRUE, only the subset of table hvrules that are enabled is extracted. |
Value
A prHvrules
object, containing plot-ready hvrules for a table, or
NULL if none have been defined.
Update the Hvrules of a Plot-Ready or Plotted Table
Description
Update the hvrules component of a plot-ready (prTable
) or plotted
(pltdTable
) table object. This is an internal function, not
intended to be called by package users.
Usage
hvrules(x) <- value
Arguments
x |
A plot-ready ( |
value |
A |
Value
An object like x
, with updated hvrules.
Get the Identifier Strings for Parts or Elements of a Table
Description
Get the unique identifier strings for elements of a plotted table, or for
parts of a textTable
.
Usage
ids(x, type, enabledOnly=TRUE)
Arguments
x |
A |
type |
Character scalar indicating the type of elements to get ID's for. May be
"entry", "block", or "hvrule" for a plotted table, or "part" for a
|
enabledOnly |
Logical scalar. If TRUE, ID's are returned only for elements that are
currently enabled in |
Details
A plotted table (pltdTable
object) has three types of elements:
entries, blocks, and hvrules. Entries are the text strings (and
associated properties) displayed in table cells. Blocks are rectangular
sets of contiguous table cells. And hvrules are spacers, with or without
a visible line (or "rule"), used to separate or group table rows and
columns.
Each element has an ID string, unique within an element type, and this function returns a vector of those strings.
A textTable
has parts ("title", "subtitle", "rowhead", etc.), and
this function just returns the vector of the part ID's.
Value
A character vector of identifiers.
See Also
elements
, which returns a data frame with full information
about each element of a plotted table.
Examples
ttbl <- textTable(iris2_tab)
# Just the names of the standard table parts:
ids(ttbl)
ptbl <- plot(ttbl)
# ID's of all the blocks defined for the table:
ids(ptbl, type="block", enabledOnly=FALSE)
# ID's of the blocks that are enabled for display (by default, none):
ids(ptbl, type="block", enabledOnly=TRUE)
A Reshaped Version of Anderson's Iris Data
Description
This is the same as R's built-in iris
data set, but reshaped into
“long” format. It contains four measurements for 50
flowers from each of three species of iris.
Usage
iris2
Format
A data frame with 600 observations on the following 5 variables.
plant
a numeric vector, numbering the flowers from 1 to 150
Species
a factor with levels
setosa
versicolor
virginica
flower_part
a factor with levels
Sepal
Petal
direction
a factor with levels
Length
Width
value
a numeric vector, the measured value, in centimeters
Source
Fisher, R. A. (1936) The use of multiple measurements in taxonomic problems. Annals of Eugenics, 7, Part II, 179–188.
The data were collected by Anderson, Edgar (1935). The irises of the Gaspe Peninsula, Bulletin of the American Iris Society, 59, 2–5.
Examples
data(iris2)
str(iris2)
Table of Summary Statistics for Anderson's Iris Data
Description
A table of means and standard deviations of the four measurements per iris plant, by species.
Usage
iris2_tab
Format
A tabular
object as produced by version 0.9.6 of the tables
package by Duncan Murdoch (https://CRAN.R-project.org/package=tables
).
The table was produced with the following code, starting from the
iris2
data frame:
iris2_tab <- tables::tabular( Species*Heading()*value*Format(digits=2)*(mean + sd) ~ Heading("Flower part")*flower_part*Heading()*direction, data=iris2)
Source
Fisher, R. A. (1936) The use of multiple measurements in taxonomic problems. Annals of Eugenics, 7, Part II, 179–188.
The data were collected by Anderson, Edgar (1935). The irises of the Gaspe Peninsula, Bulletin of the American Iris Society, 59, 2–5.
See Also
Examples
if (requireNamespace("tables", quietly=TRUE)) {
print(iris2_tab) # uses print method for 'tabular' objects
}
plot(iris2_tab)
Convert a Matrix of Headers to Table Entries, with Merging of Runs
Description
Given a matrix of row or column headers, create a corresponding set of table entries, optionally with runs of repeated values merged into single entries. This is an internal utility function, not intended to be called by package users.
Usage
make_header_entries(x, xhier, which_head, offset, mergeRuns)
Arguments
x |
A character matrix containing header text. The orientation and dimensions
should match those used for storing the corresponding header in
|
xhier |
List of data frames containing information about the hierarchical
structure of the header. Function |
which_head |
Character string indicating whether |
offset |
Two-element numeric vector. The first element is the offset to be added
to row numbers of |
mergeRuns |
Numeric scalar, specifying how deeply in the header hierarchy runs of
repeated values will be merged into single entries. Thus a value of 0
means no header cells will be merged, a value of 1 means only repeats in
the outermost header layer will be merged, 2 means repeats in the
outermost two layers will be merged, and so on. (Determination of
repeated values respects the header hierarchy; see |
Details
headlayer
and level_in_layer
in the returned data frame are
based on xhier
, which is not affected by mergeRuns
. Thus
when mergeRuns
is less than the number of header layers (so some
runs are not merged), there may be multiple entries with the same
headlayer
and level_in_layer
values. Entry ID's will be
unique however.
Value
A data frame with a row for each header entry, and most of the columns
needed for a tblEntries
object. It has an additional attribute
i,j
which is a two-column matrix containing the row and column
numbers in x
associated with each entry. (Minimum i, j values are
used for entries that span multiple rows or columns.)
See Also
headerRuns
; tblEntries
and
tblBlocks
(which use this function)
Group Rows of a Table into Sets of Fixed Size
Description
Create blocks representing groups of consecutive rows of a table, of specified size. (This is an internal utility function, not intended to be called directly by package users.)
Usage
make_rowgroups(stdblks, rowheadruns, rowgroupSize)
Arguments
stdblks |
A data frame containing the standard set of table blocks created by
|
rowheadruns |
A list with one data frame per layer of row headers (from outer to inner), containing information about the hierarchical structure of the row headers. |
rowgroupSize |
Numeric scalar. If not 0 or NA, blocks will be created by grouping consecutive rows of the table body into sets of this size. |
Details
This is an internal support function for tblBlocks
and
tblHvrules
. The code relies on the standard naming of table blocks
in tblBlocks
.
When a table has many rows within a given level of the row header hierarchy, the table may be easier to read if rows are grouped into smaller sets of fixed size (groups of 5, for example), with some extra space inserted between groups. To facilitate this, this function creates blocks representing such groups. The block type is "rowblock" and subtype is "G".
Grouping respects the row header hierarchy: the innermost header layer
that has runs of repeated values is identified (layer i
say), and
grouping is done separately within each of its levels. The block
representing a row group spans all columns of the table body as well as
row header layers out to layer i-1
. Block ID's have the form
rowblock/G/i/j/k
, where j
is the level number (within layer
i
) that contains the group, and k
is the group number within
that level. Thus i
, j
, and k
are the values of
headlayer
, level_in_layer
, and group_in_level
for the
block.
However if the table has no row headers, or none of the row header layers
have runs of repeated values, table rows are simply grouped into sets of
size rowgroupSize
. headlayer
and level_in_layer
will
be NA for the group blocks, and block ID's will have the form
rowblock/G///k
, where k
is the group number (and value of
group_in_level
).
Value
An S3 object of class tblBlocks
, containing (just) the newly
created row group blocks. These have type "rowblock" and subtype "G".
If rowgroupSize
is not a finite positive value, the returned object
will have no blocks (no rows).
See Also
tblBlocks
; headerRuns
creates the list
required by argument rowheadruns
.
Table of Data from Motor Trend Magazine
Description
This is a table of selected observations and variables from the data frame
mtcars
from package datasets.
Usage
mtcars_xtab
Format
An xtableList
object as produced by version 1.8-4 of the xtable
package (https://CRAN.R-project.org/package=xtable
). The table was
produced with the following code:
data("mtcars", package="datasets") mtcars <- mtcars[, 1:6] mtcarsList <- split(mtcars, f = mtcars$cyl) ### Reduce the size of the list elements mtcarsList[[1]] <- mtcarsList[[1]][1,] mtcarsList[[2]] <- mtcarsList[[2]][1:2,] mtcarsList[[3]] <- mtcarsList[[3]][1:3,] attr(mtcarsList, "subheadings") <- paste0("Number of cylinders = ", names(mtcarsList)) attr(mtcarsList, "message") <- c("Line 1 of Message", "Line 2 of Message") mtcars_xtab <- xtable::xtableList(mtcarsList, digits = c(0,2,0,0,0,1,2), caption = "Caption to List")
Source
Henderson and Velleman (1981), Building multiple regression models interactively. Biometrics, 37, 391-411.
See Also
mtcars
Examples
ttbl <- textTable(mtcars_xtab)
plot(ttbl, rowheadInside=TRUE)
Identify Strings that Cannot be Interpreted as Numbers
Description
Identify strings in a character vector that cannot be interpreted as valid numbers. This is an internal utility function, not intended to be called by package users.
Usage
notANumber(x, result=c("logical", "values"))
Arguments
x |
A character vector. |
result |
The form of result to be returned (see VALUE). |
Details
Which character strings can or cannot be interpreted as valid numbers is
determined by the function as.numeric
. Note that the empty string
"" is considered a valid representation of NA.
Value
If result
is "logical", a logical vector as long as x
that
is TRUE for those elements that cannot be interpreted as valid numbers.
If result
is "values", a character vector containing the unique
values in x
that cannot be interpreted as valid numbers.
Paste Strings that may Include plotmath
or Markdown
Description
Paste together text strings, where one or more of the strings may contain
plotmath
expressions or markdown/HTML tags. This is an internal
function, not intended to be called by package users.
Usage
paste_text(x, ..., sep=c("plain"=" ", "plotmath"="~", "markdown"=" "))
Arguments
x , ... |
One or more character vectors or data frames. Data frames should contain
columns |
sep |
Character vector containing strings to be inserted between text from
different arguments when pasting them together. It may have one string
per valid |
Details
"plotmath" and "markdown" strings cannot be pasted together. When a
"plain" string is pasted together with one of the other types, the result
will have the textspec
value of the non-plain text.
If a set of "plain" text strings to be pasted together use different fontfaces, the final text will use plotmath or markdown to accomodate the mixed faces.
Value
A data frame with columns text
, textspec
, and
fontface
. The number of rows equals the number in the longest data
frame argument. text
contains the row-by-row pasted-together text
from the arguments, and textspec
specifies the content type of each
row. fontface
is NA when textspec
is "plotmath", 1 when
textspec
is "markdown", and taken from x
when
textspec
is "plain".
Note
Changing "plain" text to "markdown" is incomplete. For example, literal
*
or _
will be misinterpreted as markdown codes.
See Also
Display a pltdtable
Object on a Graphics Device
Description
Display a pltdTable
object on a graphics device. This is an alias
for print.pltdTable
. This is an internal function, not intended to
be called by package users.
Usage
## S3 method for class 'pltdTable'
plot(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to |
Value
x
, invisibly.
See Also
A Plot Method for prentries
Objects
Description
A plot method for prEntries
objects, displaying tables using
ggplot2
graphics. This is an internal function, not intended to be
called by package users.
Usage
## S3 method for class 'prEntries'
plot(x, hvruleStyle=tablesggOpt("hvruleStyle"),
blockStyle=tablesggOpt("blockStyle"), scale=attr(x, "current_scale"),
rowgroupSize=0, ...)
Arguments
x |
A |
hvruleStyle , blockStyle , scale , rowgroupSize |
Arguments used to control the appearance of the plot. See the
documentation for |
... |
Additional arguments, passed to |
Details
This function assumes that the standard set of blocks and hvrules is to be
used when plotting the table entries in x
. For more control over
blocks and hvrules, create them directly (for example by functions
tblBlocks
and prHvrules
) and then combine them with x
into a plot-ready table (function prTable
).
Value
An object of S3 class pltdTable
, inheriting from ggplot
.
See plot.textTable
for details about this object. There is a print
(display) method for this class, or the object can be modified in the
usual ggplot
way before display.
See Also
plot.textTable
, print.pltdTable
A Plot Method for prtable
Objects
Description
A plot method for prTable
objects, to display tables using
ggplot2
graphics. This is an internal function, not intended to be
called by package users.
Usage
## S3 method for class 'prTable'
plot(x, plot.margin=tablesggOpt("plot.margin"), sizeAdjust=c(1.0,
1.0), ...)
Arguments
x |
A |
plot.margin |
Numeric vector of length 4, giving the amount of padding to be added outside the top, right, bottom, and left sides of the table, in millimeters. |
sizeAdjust |
Two-element numeric vector containing multipliers to adjust the calculated absolute size of table text. The first element is applied to the horizontal dimension and the second to the vertical dimension. See DETAILS. |
... |
Other arguments, ignored with a warning. (Included for compatibility with
the |
Details
The implicit coordinate system for the plot is in millimeters, with the
origin at the upper left corner of the _table_ (which may differ from the
upper left corner of the plot due to plot.margin
), and
y-coordinates increasing downward. All sizes and dimensions are in
millimeters except font size, which is in points.
The print method for pltdTable
objects attempts to draw the table
at its natural size, as given by attribute size_mm
. (Function
pltdSize
provides convenient access to this attribute, in
user-controllable units.) However the calculated size depends slightly on
the graphics device being used (see ?Devices
). sizeAdjust
may be used to compensate for this difference when a plotted table object
created using one device is to be displayed with a different one.
This function checks the enabled
field of the entries
,
blocks
, and hvrules
components of x
. Elements for
which enabled
is FALSE are not displayed, and their size is treated
as 0 when laying out the table.
Value
An object of S3 class pltdTable
, inheriting from ggplot
.
(However if x
has no enabled entries to plot, the returned value is
NULL, with a warning.) There is a print (display) method for this class,
or the object can be modified in the usual ggplot
way before
display.
The object has attributes plot.margin
and sizeAdjust
(equal
to the arguments), and size_mm
(the width and height of the plot,
in millimeters). size_mm
is calculated after applying
sizeAdjust
, and includes both the table and any margins specified
by plot.margin
.
The object also has attributes colBoundaries
and
rowBoundaries
giving the coordinates of the boundaries between
columns and between rows, again in mm, and after applying
sizeAdjust
.
The object also has attribute prTable
, the plot-ready table object
x
. This is to allow convenient updating of the display properties
of the table.
See Also
prTable
, pltdSize
,
print.pltdTable
, Devices
,
calc_rcsize
, coord_justif
A Plot Method for tabular
Objects
Description
A plot method for tabular
objects, which represent a 2D data
summary table. The table is displayed using ggplot2
graphics.
Usage
## S3 method for class 'tabular'
plot(x, ...)
Arguments
x |
An object of class |
... |
Additional arguments passed to |
Details
This function is a simple wrapper that first converts x
to a
textTable
object, and then plots that object.
Value
An object of S3 class pltdTable
, inheriting from ggplot
.
See the documentation for plot.textTable
for more information.
See Also
plot.textTable
, format.tabular
,
textTable.tabular
A Plot Method for tblentries
Objects
Description
A plot method for tblEntries
objects, displaying tables using
ggplot2
graphics. This is an internal function, not intended to be
called by package users.
Usage
## S3 method for class 'tblEntries'
plot(x, entryStyle=tablesggOpt("entryStyle"), ...)
Arguments
x |
A |
entryStyle |
Optional |
... |
Additional arguments passed to |
Details
This function is a wrapper that simply converts x
to "plot-ready"
table entries (a prEntries
object) by applying the style specified
by entryStyle
, and then calls the plot method for prEntries
objects.
This function assumes that the standard set of blocks and hvrules is to be
used when plotting the table entries in x
. For more control over
blocks and hvrules, create them directly (for example by functions
tblBlocks
and tblHvrules
) and then combine them with
x
into a plot-ready table (functions prEntries
,
prHvrules
, prTable
).
Value
An object of S3 class pltdTable
, inheriting from ggplot
.
See plot.textTable
for details about this object. There is a print
(display) method for this class, or the object can be modified in the
usual ggplot
way before display.
See Also
plot.textTable
, print.pltdTable
A Plot Method for texttable
Objects
Description
A plot method for textTable
objects, displaying tables using
ggplot2
graphics.
Usage
## S3 method for class 'textTable'
plot(x, title=NULL, subtitle=NULL, foot=NULL, rowheadLabels=NULL,
entryStyle=tablesggOpt("entryStyle"),
hvruleStyle=tablesggOpt("hvruleStyle"),
blockStyle=tablesggOpt("blockStyle"), scale=1.0, mergeRuns=c(TRUE,
TRUE), rowheadInside=FALSE, rowgroupSize=0,
plot.margin=tablesggOpt("plot.margin"), sizeAdjust=c(1.0, 1.0), ...)
Arguments
x |
A |
title , subtitle , foot |
Optional character vectors of annotation for the table. NULL means to
leave the current annotation unchanged (the default); |
rowheadLabels |
Optional character vector or 1-row matrix specifying labels for the row
header columns of the table. NULL means to leave the current value
unchanged (the default); |
entryStyle , hvruleStyle , blockStyle |
Optional |
scale |
Numeric multiplier used to increase or decrease the displayed size of the table, with all elements scaled proportionately. If it has length two, the first element applies to table entries and blocks, and the second to hvrules. |
mergeRuns |
Two-element logical vector, the first element applying to row headers, the second to column headers. If TRUE (the default) then header cells that contain runs of the same value will be merged into a single entry that spans multiple rows or columns. |
rowheadInside |
Logical scalar. If TRUE, the outermost layer of row headers is moved inside the table by using its levels to divide the table into groups of rows, with each group labeled by their level. |
rowgroupSize |
Numeric scalar. If greater than 0, consecutive rows of the table body will be grouped into sets of this size, and extra space may be inserted between groups to improve readability. See DETAILS. |
plot.margin |
Numeric vector of length 4, giving the amount of padding to be added
outside the top, right, bottom, and left sides of the table, in
millimeters. The default is taken from |
sizeAdjust |
Two-element numeric vector containing multipliers to adjust the calculated absolute size of table text. The first element is applied to the horizontal dimension and the second to the vertical dimension. (It should not be necessary to change this.) |
... |
Other arguments, ignored with a warning. (Included for compatibility with
the |
Details
textTable
objects are the fundamental structure for representing
tables in the tablesgg
package. This function creates a
publication-quality plot of such a table that can be displayed on any of
R's graphics devices. Plotting is based on the ggplot2
graphics
system, and the resulting plot object can be saved or manipulated in the
usual ggplot
way.
A feature of the plotted table produced by this function is that it has a
well-defined physical size, in millimeters, given by the attribute
size_mm
. This natural size is determined by the graphical
properties specified with arguments entryStyle
and
hvruleStyle
, and can be rescaled up or down with the scale
argument. There is a special print (display) method for pltdTable
objects that ensures that the table is displayed at the correct size,
independent of the size of the graphics device on which it is drawn.
The plotted table can be modified by using the props<-
set of
functions to update graphical properties of selected table entries,
hvrules, or blocks. This includes disabling them (so that they are
excluded from the plot), or re-enabling disabled elements. For broader
changes there is an update
method for pltdTable
objects to
change styles or plot scaling. See update.pltdTable
for more
information.
Value
An object of S3 class pltdTable
, inheriting from ggplot
.
The object has attributes plot.margin
and sizeAdjust
(equal
to the arguments), and size_mm
(the width and height of the plot,
in millimeters). size_mm
is calculated after applying scale
and sizeAdjust
, and includes both the table and any margins
specified by plot.margin
.
The object also has attributes colBoundaries
and
rowBoundaries
giving the coordinates of the boundaries between
columns and between rows, again in millimeters, and after applying
scale
and sizeAdjust
.
The object also has attribute prTable
. This a "plot-ready" version
of the table, after applying the arguments provided to this function to
x
, but before processing by ggplot
. It is included to allow
convenient updating of the display properties of the table via
props<-
functions.
See Also
textTable
, styleObj
,
tablesggOpt
, styles_pkg
,
print.pltdTable
, props<-
,
update.pltdTable
Examples
# Start with a 'textTable':
ttbl <- textTable(iris2_tab)
# Default display:
plot(ttbl)
# Add annotation:
plot(ttbl, title="The iris data", subtitle="Summary statistics by species",
foot="sd = standard deviation")
# Smaller version:
plot(ttbl, title="The iris data", subtitle="Summary statistics by species",
foot="sd = standard deviation", scale=0.8)
# Use a more "spread out" style for table entries:
plot(ttbl, entryStyle=styles_pkg$entryStyle_pkg_2)
# Internal row header labels:
plot(ttbl, rowheadInside=TRUE)
# Show effect of 'plot.margin' by putting a box around the table:
# -- default
plt <- plot(ttbl) +
ggplot2::theme(plot.background=ggplot2::element_rect(color="blue",
linewidth=1))
plt
# -- wider margin
plt <- plot(ttbl, plot.margin=c(15, 15, 15, 15)) +
ggplot2::theme(plot.background=ggplot2::element_rect(color="blue",
linewidth=1))
plt
# Data frame listing with rows in groups of 5:
plot(textTable(head(iris2, 15)), rowgroupSize=5)
Width and Height of a pltdtable
Object
Description
Width and height of a pltdTable
object.
Usage
pltdSize(x, units=c("mm", "inches", "cm"))
Arguments
x |
An object of class |
units |
String specifying the units in which size is to be returned. May be abbreviated. |
Details
This function returns the size, after any scaling, of a plotted table, in physical units. The default units are millimeters to be consistent with other dimensions used in plotting tables. Inches may be useful because that is what R's graphics device functions use.
The size of a plot can depend slightly on the graphics device used to create or render it. The device name used internally to create the plot is included as an attribute of the returned value.
Value
Two-element numeric vector containing the (width, height) of the plot. It
has attributes units
and device
.
See Also
Examples
plt <- plot(iris2_tab, title="Summary statistics for the iris data")
pltdSize(plt) # width, height in millimeters
# Open a graphics device just the right size to hold the table:
sz <- pltdSize(plt, units="in")
dev.new(width=sz[1], height=sz[2], noRStudioGD=TRUE)
plt
Assign Graphical Properties to Table Blocks
Description
Assign graphical properties to table blocks (rectangular sets of table
cells), based on a style and scaling factor. This creates plot-ready
(pr
) blocks. This is an internal function, not intended to be
called by package users.
Usage
prBlocks(x, style=tablesggOpt("blockStyle"), scale=1.0)
Arguments
x |
A |
style |
A |
scale |
Numeric multiplier used to increase or decrease the displayed size of
certain block properties, relative to the natural size implied by
|
Details
The graphical properties available for a block, and their types, are
defined in object grProps
. They include both color and alpha used
to fill the area occupied by the block, and the color and thickness of the
border drawn around the block. When rendering a table, blocks are drawn
first so that they will not obscure entries or hvrules.
See styleObj
for information about how a style is specified, and
how it is applied to blocks. Note that individual style specifications
(rows) in style
are applied to x
in order. If a block
matches more than one style
row, the last matching row will
override the earlier ones.
All blocks are disabled by default; i.e., they will not be displayed when
a table is plotted. Selected blocks can be enabled by editing a
prBlocks
object like a data frame, or by modifying an existing plot
using the props<-
function.
Value
An object of S3 classes prBlocks
, tblBlocks
, and
data.frame
. It has the same rows and columns as x
(one row
per block), plus additional or updated columns containing the graphical
properties to use for each block (shading and borders); logical column
enabled
(indicating whether the block is to be made visible when
the table is rendered, by shading and/or a border); and column
style_row
(the number of the last row in style
that the
block matched, or NA if it matched none).
Row names for the data frame are set equal to block id
. The object
has several additional attributes: current_scale
and style
,
based on the scale
and style
arguments after applying
defaults; and rowgroupSize
and rowheadInside
, copied from
x
.
See Also
elements
documents the descriptors and graphical properties
for blocks. tblBlocks
defines a default set of blocks that
reflect the logical structure of the table. styleObj
creates styles.
Assign Graphical Properties to Table Entries
Description
Assign graphical properties to table entries, based on a style and scaling
factor. This creates fully plot-ready (pr
) entries. This is an
internal function, not intended to be called by package users.
Usage
prEntries(x, style=tablesggOpt("entryStyle"), scale=1.0)
Arguments
x |
A |
style |
A |
scale |
Numeric multiplier used to increase or decrease the displayed size of
entries, relative to the natural size implied by |
Details
The graphical properties available for an entry, and their types, are
defined in object grProps
. They include both properties for the
entry text itself (size, font, color, etc) and for the cell(s) containing
the entry (background color, border thickness and color).
Justification of text within a cell is specified by properties
hjust
and vjust
. Their interpretation is with respect to
the boundaries of the cell: 0 means justification toward the left/top of
the cell, 1 means toward the right/bottom, and 0.5 means centered.
See styleObj
for information about how a style is specified, and
how it is applied to entries. Note that individual style specifications
(rows) in style
are applied to x
in order. If an entry
matches more than one style
row, the last matching row will
override the earlier ones.
One can also assign or modify graphical properties directly, without using
a style, by editing a prEntries
object like a data frame.
Properties in an existing plot can also be modified using the
props<-
set of functions.
Value
An object of S3 classes prEntries
, tblEntries
, and
data.frame
. It has the same rows and columns as x
(one row
per entry), plus additional or updated columns containing the graphical
properties to use for each entry, plus a column style_row
(the
number of the last row in style
that the entry matched, or NA if it
matched none).
Row names for the data frame are set equal to block id
. The object
has several additional attributes: current_scale
and style
,
based on the scale
and style
arguments after applying
defaults; and mergeRuns
, rowheadInside
, rowhier
, and
colhier
, copied from x
.
See Also
elements
documents the descriptors and graphical properties
for blocks. tblEntries
; styleObj
creates
styles; as.prEntries
.
Create Hvrules and Assign Them Graphical Properties
Description
Create horizontal and vertical rules (hvrules) for a table, based on
blocks of table entries. hvrules also provide a way to insert extra space
between rows or columns of the table, without drawing a line. Assign
graphical properties to the hvrules using a style and a scaling factor.
This creates fully plot-ready (pr
) hvrules. This is an internal
function, not intended to be called by package users.
Usage
prHvrules(x, style=tablesggOpt("hvruleStyle"), scale=1.0)
Arguments
x |
A |
style |
A |
scale |
Numeric multiplier used to increase or decrease the displayed size of
hvrules, relative to the natural size implied by |
Details
A horizontal rule (hrule) consists of a narrow, horizontally-oriented rectangle, possibly with a horizontal line drawn within it. The rectangle is inserted _between_ rows of the table, and therefore increases the size of the table by an amount equal to its height. Thus an hrule can be used to insert extra space between table rows, with or without including a line. Similarly a vertical rule (vrule) is a narrow, vertically-oriented rectangle, possibly with a vertical line drawn within it. The rectangle is inserted between columns of the table and increases the table's width.
This function creates four hvrules per non-empty block in x
: two
hrules that run along the top and bottom sides of the block, and two
vrules that run along the left and right sides of the block. It then
applies style
to assign them graphical properties. See
styleObj
for details of how matching individual hvrules to
graphical properties is done.
The graphical properties available for an hvrule are defined in object
grProps
. They include the amount of space added to the table by
the hvrule, and properties for any line drawn within it (line type, color,
thickness, etc).
All hvrules are initially disabled; i.e., they will not be displayed and
will not take up any physical space when a table is plotted. Once an
hvrule has been assigned graphical properties from style
, its
enabled
value will be set to TRUE. However hvrules associated with
blocks that contain no enabled entries (as reported by
x$had_enabled_entries
) always have enabled
set to FALSE.
Two hvrules may occupy the same location in the table. For example if the right edge of block A is adjacent to the left edge of block B, and the blocks span the same rows, then the vrule on the "right" side of A will have the same location as the vrule on the "left" side of B.
Value
An object of S3 class prHvrules
, which is a data frame with each
row specifying one hvrule for the table. If there are no hvrules, the
data frame will have no rows. Column descriptions are in the
documentation for the elements
function, except for:
style_row |
Row number in |
Row names for the data frame are set equal to id
. The object also
has attributes current_scale
and style
, based on the
scale
and style
arguments after applying defaults.
See Also
elements
documents the descriptors and graphical properties
for blocks; tblBlocks
defines a default set of blocks that
reflect the logical structure of the table. styleObj
creates styles.
Create or Update a Fully Styled Table Ready for Plotting
Description
Create or update a prTable
object, a fully styled (plot-ready)
table. This is an S3 generic. It and its methods are internal functions,
not intended to be called by package users.
Usage
prTable(x, ...)
Arguments
x |
An object to be converted to a plot-ready table. |
... |
Additional arguments passed to specific methods. |
Value
An object of S3 class prTable
. See prTable.prEntries
for
the structure of this object.
Extract/Update a Plot-Ready Table from a Plotted Table
Description
Extract the prTable
(plot-ready table) object from a plotted table.
This is an internal function, not intended to be called by package users.
Usage
## S3 method for class 'pltdTable'
prTable(x, ...)
Arguments
x |
A |
... |
Ignored, with a warning. (Included for compatibility with the generic.) |
Value
An object of S3 class prTable
, a plot-ready table. See
prTable.prEntries
for the structure of this object.
Create a Plot-Ready Table from Plot-Ready Entry, Block, and Hvrule Objects
Description
Create a plot-ready table from plot-ready entry, block, and hvrule objects. This is an internal function, not intended to be called by package users.
Usage
## S3 method for class 'prEntries'
prTable(x, entries=x, blocks=prBlocks(tblBlocks(x)), hvrules, ...)
Arguments
x |
A |
entries |
An alias for |
blocks |
A |
hvrules |
A |
... |
Ignored, with a warning. (Included for compatibility with the generic.) |
Details
This function allows the creation of a plot-ready table directly from its
entry, block, and hvrule components. A prTable
object can be
updated with new styles or scales for its components by calling the
.prTable
method.
Value
An object of S3 class prTable
, a plot-ready table. This is a list
with components:
entries |
A |
blocks |
A |
hvrules |
A |
It has attribute current_scale
, a numeric vector of length 2. The
first element is for entries
, the second for hvrules
.
See Also
prEntries
, prBlocks
, prHvrules
.
Add or Remove the Prefix Associated with textspec
Values
Description
Add or remove special, textspec
-related prefixes from text strings.
This is an internal utility function, not intended to be called by package
users.
Usage
prefix_text(x, spec, action)
Arguments
x |
Character vector to which special prefixes are to be added or removed. |
spec |
Character vector of valid |
action |
Character scalar, either "add" or "remove", depending on whether the
special prefix is to be added or removed from |
Details
Currently supported textspec
values and the associated prefixes
are: "plain" (no prefix); "plotmath" (prefix MATH_
); and "markdown"
(prefix MKDN_
).
Value
Character vector like x
, with prefixes added or removed. NA values
in x
remain NA.
See Also
spec_from_text
to derive spec
by looking for special
prefixes in text strings.
Print (Draw) a pltdtable
Object
Description
Print method for pltdTable
objects, to display the table on the
currently active graphics device. It draws the table at its natural size,
as determined by the font size and dimensions specified by the styles used
to create the table, and after applying any scale factors.
Usage
## S3 method for class 'pltdTable'
print(x, scale=NULL, newpage=TRUE, position=c(0.5, 0.5),
vpx=grid::unit(0.5, "npc"), vpy=grid::unit(0.5, "npc"),
just="center", ...)
Arguments
x |
A |
scale |
Optional numeric multiplier used to increase or decrease the displayed
size of the table, relative to the natural size implied by its styles.
The default is to keep the current scaling in |
newpage |
Whether to draw the table on the current page of the graphics device, or on a new blank page. |
position |
Two-element numeric or character vector specifying the horizontal and vertical position of the table on the page. A value of 0 means left/bottom justification, 1 means right/top justification, and intermediate values shift the table linearly between those limits. If a character vector, valid values are "left", "center", "right" for horizontal position, and "bottom", "center", "top" for vertical position. The default is to center the table on the page. |
vpx , vpy , just |
Alternatives to |
... |
Optional additional arguments passed to |
Details
The purpose of a special print method for pltdTable
objects is to
set a particular viewport size, so that the table is displayed at its
natural size, adjusted for scale
. Once the viewport is set, the
table is drawn using the usual ggplot
print method.
Note that scaling of table size is not cumulative. If x
has
already been scaled (say, by a factor of 0.8), and argument scale
is set to 0.9, then the table will be displayed at 0.9 times its natural
size, not 0.9*0.8 = 0.72.
The default is that the table is drawn centered in the current graphics
viewport (usually the whole graphics device surface). This can be changed
using either the position
or the just
, vpx
and
vpy
arguments. grid::viewport
uses the latter four numbers
to specify position; see its documentation for details. The
position
argument simplifies this to use just two numbers, each in
[0, 1]. It assumes one rarely wants to have parts of the table outside
the boundary of the page, so 0 corresponds to putting the table snug
against the left or bottom edge, 1 corresponds to putting it against the
right or top edge, and intermediate values simply linearly interpolate
between those limits.
Value
x
, invisibly.
See Also
plot.textTable
, grid::viewport
,
ggplot2::print.ggplot
Examples
# Start with different ways of arranging the Titanic data:
data(Titanic, package="datasets")
ftbl1 <- ftable(Titanic, row.vars=c("Class", "Sex"), col.vars="Survived")
ftbl2 <- ftable(Titanic, row.vars=c("Age", "Sex", "Survived"),
col.vars="Class")
ftbl3 <- ftable(Titanic, row.vars=c("Sex", "Class"),
col.vars=c("Age", "Survived"))
plt1 <- plot(textTable(ftbl1))
plt2 <- plot(textTable(ftbl2))
plt3 <- plot(textTable(ftbl3))
plt4 <- plot(textTable(ftbl3), rowheadInside=TRUE)
# Center plots in the four quadrants of the page:
print(plt1, vpx=0.25, vpy=0.75)
print(plt2, vpx=0.75, vpy=0.75, newpage=FALSE)
print(plt3, vpx=0.25, vpy=0.25, newpage=FALSE)
print(plt4, vpx=0.75, vpy=0.25, newpage=FALSE)
# Single plot at different sizes, pushed to corners of the page:
print(plt2, scale=0.8, position=c("left", "top"))
print(plt2, scale=1.2, position=c("right", "bottom"), newpage=FALSE)
Print the Dimensions and Display Options of a Plotted Table
Description
Print method for summary.pltdTable
objects. The dimensions and
display options of a plotted table are printed. This is an internal
function, not intended to be called directly by package users.
Usage
## S3 method for class 'summary.pltdTable'
print(x, ...)
Arguments
x |
A |
... |
Additional arguments, ignored with a warning. (Included for compatibility with the generic.) |
Value
x
is returned, invisibly.
Print the Dimensions of a Table and Its Parts
Description
Print method for summary.textTable
objects. The dimensions of a
table and its parts are printed. This is an internal function, not
intended to be called directly by package users.
Usage
## S3 method for class 'summary.textTable'
print(x, ...)
Arguments
x |
A |
... |
Additional arguments, ignored with a warning. (Included for compatibility with the generic.) |
Value
x
is returned, invisibly.
Update Graphical Properties for Selected Table Elements
Description
Update the graphical properties for selected table entries, hvrules, or blocks in a plotted table.
Usage
props(x, id=NULL, regex=NULL, setEnabled=TRUE, mustMatch=TRUE,
...) <- value
Arguments
x |
A |
id |
Optional character vector of the ID's of the elements (or of table parts containing the elements) to be modified. |
regex |
Optional character string containing a regular expression. This will be
used to find table entries whose text matches the regular expression.
(Only valid when |
setEnabled |
Logical scalar. If TRUE then any element whose properties are updated by
this function will have its |
mustMatch |
Logical scalar. If TRUE, any strings in argument |
... |
Additional arguments passed to |
value |
An |
Details
There are three similar functions that can be used to modify the graphical
properties of table elements: props<-
, propsa<-
, and
propsd<-
. They differ only in how one specifies which elements are
to be modified. props<-
uses element or block ID's, or searches
the text content of entries. propsa<-
uses explicit row and column
numbers within the augmented row-column grid. propsd<-
uses the
values of element descriptors (as described in ?elements
).
The type of elements that are updated is determined by value
: if
value
is an element_entry
or element_refmark
object
then entries are updated; if it is an element_hvrule
object then
hvrules are; if it is an element_block
object then blocks are. See
the documentation of those functions for the available properties. As an
example, element_entry(color="red", fontface=3, hpad=rel(0.8))
specifies that all the updated entries will be displayed in red italics,
and padding on their left and right will be reduced to 80% of the current
amount. Any graphical properties not mentioned in the call that creates
the element_*
object are left unchanged.
There are two special properties: enabled
and textspec
(the
latter only for entries). enabled
is a logical scalar. If
enabled
is set to FALSE the selected elements will not be
displayed, and disabled entries/hvrules will not be allocated any space in
the plotted table. textspec
is a character string, one of "plain",
"plotmath", or "markdown". If "plotmath", entry text will be treated as
an expression that allows display of mathematical symbols and notation,
including subscripts and superscripts (see ?plotmath
). If
"markdown", entry text may contain markdown or HTML tags that affect the
appearance of the displayed text. (This requires the ggtext
package, and only a subset of HTML tags is supported. See the
ggtext
package documentation for more information.)
element_refmark
is used to add a reference mark to the selected
entries. (A reference mark is a symbol placed before or after entry text
to indicate cross-references; e.g. for footnotes.) It may also update any
of the graphical properties accepted by element_entry
, except
textspec
and text
.
Arguments id
and regex
indicate which elements are to be
updated. When value
indicates that table entries are to be
modified, id
may specify the ID's of individual entries or the ID's
of table parts or blocks. In the latter case, all entries completely or
partially contained in the parts or blocks are selected. Thus, for
example, specifying id="table"
will update every entry in the
table, while id="body"
will update only entries in the table body.
Argument regex
is only valid for modifying table entries;
grepl
is used to identify the entries whose text matches the
regex
pattern. If both id
and regex
are specified,
then only entries selected by both are modified.
When value
indicates that hvrules are to be modified, id
should contain the ID's of individual hvrules and/or table blocks. In the
latter case, any hvrule associated with a listed block (that is, the
hvrule was defined as running along one of the sides of the block) will be
updated.
When value
indicates that blocks are to be modified, id
should contain the ID's of individual table blocks.
See ?elements
for the format of element ID strings.
This function overrides graphical properties in x
that may have
been set by a style. Therefore the value of style_row
is set to NA
for any elements whose properties are updated by this function.
Value
An object like x
, with updated graphical properties for the
selected elements.
See Also
element_entry
, element_refmark
,
element_hvrule
, element_block
,
ids
, propsa<-
, propsd<-
Examples
ttbl <- textTable(iris2_tab, title="The iris data",
subtitle=c("Summary statistics by species",
"A second subtitle line"),
foot="sd = standard deviation")
plt <- plot(ttbl)
# Change properties of elements:
props(plt, id="body") <- element_entry(fontface=3, fill="gray85")
# This may include changing text:
props(plt, id="subtitle,2") <- element_entry(text="Properties changed by 'props<-'",
fill="gray85")
# Use property 'enabled' to control whether an element is displayed:
props(plt, id="rowhead_and_body_bottom") <- element_hvrule(enabled=FALSE)
plt
# Add reference marks to entries with abbreviation "sd":
plt <- plot(ttbl)
props(plt, regex="^sd$") <- element_refmark(mark="*", side="after")
props(plt, regex="^sd =") <- element_refmark(mark="*", side="before")
plt
# If both 'id' and 'regex' are specified only the intersection is modified:
plt <- plot(ttbl)
props(plt, regex="^sd$", id="rowblock/B/2/1") <-
element_refmark(mark="*", side="after")
props(plt, regex="^sd =") <- element_refmark(mark="*", side="before")
plt
Update Graphical Properties for Selected Table Elements
Description
Update the graphical properties for selected table entries, hvrules, or blocks in a plotted table. This is an internal function, not intended to be called by package users.
Usage
props_mod(x, value, id=NULL, e=NULL, arows=NULL, acols=NULL,
setEnabled=TRUE)
Arguments
x |
A |
value |
An |
id , e , arows , acols |
Arguments that identify which elements in |
setEnabled |
Logical scalar. If TRUE then any element whose properties are updated by
this function will have its |
Details
This is a backend for public functions props<-
, propsa<-
,
and propsd<-
. The latter are wrappers that accept different sets
of arguments to specify which elements are to be updated. See their
documentation for the details.
This function overrides graphical properties in x
that may have
been set by a style. Therefore the value of style_row
is set to NA
for any elements whose graphical properties are updated by this function.
Value
An object like x
, with updated graphical properties for the
selected elements.
See Also
Update Graphical Properties for Selected Table Elements
Description
Update the graphical properties of table elements in selected rows and columns of a plotted table.
Usage
propsa(x, arows=NULL, acols=NULL, setEnabled=TRUE) <- value
Arguments
x |
A |
arows , acols |
Numeric vectors of row and column numbers in the table's augmented row-column grid. The default value of NULL means all rows or columns. Use half-integer values to refer to the locations of horizontal or vertical rules running between rows or columns. |
setEnabled |
Logical scalar. If TRUE then any element whose properties are updated by
this function will have its |
value |
An |
Details
There are three similar functions that can be used to modify the graphical
properties of table elements: props<-
, propsa<-
, and
propsd<-
. They differ only in how one specifies which elements are
to be modified. props<-
uses element or block ID, or searches the
text content of entries. propsa<-
uses explicit row and column
numbers within the augmented row-column grid. propsd<-
uses the
values of element descriptors (as described in ?elements
).
The type of elements that are updated is determined by value
: if
value
is an element_entry
or element_refmark
object
then entries are updated; if it is an element_hvrule
object then
hvrules are; if it is an element_block
object then blocks are. See
the documentation for props<-
for discussion of their use.
For this function the selected elements are those which are (a) completely
contained within the rows listed in arows
and the columns listed in
acols
; and (b) of a type (entry, block, or hvrule) corresponding to
the class of value
. For (a), arows
and acols
are
treated as _sets_ of row/column numbers, not _ranges_. For example, a
horizontal rule running between rows 3 and 4 will not be selected by
arows=c(3, 4)
; the value 3.5 must be included in arows
.
The helper functions arow
and acol
provide a partial bridge
between this function and props<-
. They return row and column
numbers associated with particular element IDs, or with specified values
of the row and column headers. For example, propsa(plt,
arows=arow(plt, id="body"), acols=acol(plt, id="body"))
is equivalent to
props(plt, id="body")
. See the examples below for cases where the
combination of propsa<-
and arow
/acol
is more
convenient than props<-
alone.
This function overrides graphical properties in x
that may have
been set by a style. Therefore the value of style_row
is set to NA
for any elements whose properties are updated by this function.
Value
An object like x
, with updated graphical properties for the
selected elements.
See Also
element_entry
, element_refmark
,
element_hvrule
, element_block
,
arow
, acol
, props<-
,
propsd<-
Examples
plt <- plot(iris2_tab, title="Summary statistics for the iris data")
plt2 <- plt
# Change the title to italics:
propsa(plt2, arows=1) <- element_entry(fontface=3)
# Change the vertical rule between row header and body from empty to
# a solid line:
propsa(plt2, acols=2.5) <- element_hvrule(linetype=1, color="black",
size=0.5)
# Put all the mean values in bold face:
propsa(plt2, arows=arow(plt2, hpath=c(NA, "mean")),
acols=acol(plt2, id="body")) <- element_entry(fontface=2)
plt3 <- plt
# Use shading to highlight the rows for the 'versicolor' species:
propsa(plt3, arows=arow(plt3, hpath=c("versicolor"))) <-
element_block(fill="gray85")
# Compare tables before and after modification:
print(plt, vpx=0.25, vpy=0.75)
print(plt2, vpx=0.75, vpy=0.75, newpage=FALSE)
print(plt3, vpx=0.5, vpy=0.25, newpage=FALSE)
# Striping every other row in a data frame listing (must include row names):
data(mtcars, package="datasets")
plt <- plot(textTable(head(mtcars, 10),
title="Partial listing of the 'mtcars' data frame"))
ar <- arow(plt, id="body")
propsa(plt, arows=ar[ar %% 2 == 0]) <- element_block(fill="gray85")
plt
Update Graphical Properties for Selected Table Elements
Description
Update the graphical properties for table elements selected based on the values of element descriptors.
Usage
propsd(x, subset=NULL, setEnabled=TRUE) <- value
Arguments
x |
A |
subset |
An expression that when evaluated gives a logical vector indicating which elements should be updated; missing values are taken as FALSE. See DETAILS. |
setEnabled |
Logical scalar. If TRUE then any element whose properties are updated by
this function will have its |
value |
An |
Details
There are three similar functions that can be used to modify the graphical
properties of table elements: props<-
, propsa<-
, and
propsd<-
. They differ only in how one specifies which elements are
to be modified. props<-
uses element or block ID's, or searches
the text content of entries. propsa<-
uses explicit row and column
numbers within the augmented row-column grid. propsd<-
uses the
values of element descriptors (as described in ?elements
).
The type of elements that are updated is determined by value
: if
value
is an element_entry
or element_refmark
object
then entries are updated; if it is an element_hvrule
object then
hvrules are; if it is an element_block
object then blocks are. See
the documentation for props<-
for discussion of their use.
Internally entries, hvrules, and blocks are represented as data frames,
with one row per element, and columns describing their content, position,
and structural role in the table. (See ?elements
for a list of the
descriptor columns for each type of element.) Argument subset
is
an expression involving those columns that evaluates to a logical vector;
the elements for which this vector is TRUE will be selected. (NA in the
logical vector is treated as FALSE.) Thus the subset
argument
works in the same way as R's built-in subset
function to select
rows from a data frame. For example subset=(part=="body" &
type=="numeric")
will update graphical properties for all entries in the
table body that have been tagged as representing numbers. And
subset=(direction=="hrule")
will update graphical properties for
horizontal rules but not vertical rules.
To update every element (of the type implied by value
) in the
table, set subset=TRUE
. To update just the currently enabled
elements, set subset=enabled
.
Note: Standard processing generates hvrules for all four sides of every
block in the table. Since generally one doesn't want to display the
blocks themselves nor most of those hvrules, they are all disabled by
default. Therefore if using subset=TRUE
when updating hvrules or
blocks, also set setEnabled
to FALSE to avoid enabling and
displaying them all.
This function overrides graphical properties in x
that may have
been set by a style. Therefore the value of style_row
is set to NA
for any elements whose graphical properties are updated by this function.
Value
An object like x
, with updated graphical properties for the
selected elements.
See Also
element_entry
, element_refmark
,
element_hvrule
, element_block
,
elements
, props<-
, propsa<-
Examples
ttbl <- textTable(iris2_tab, title="The iris data",
subtitle=c("Summary statistics by species"),
foot="sd = standard deviation")
plt <- plot(ttbl)
propsd(plt, subset=(enabled)) <- element_hvrule(color="red")
propsd(plt, subset=(part == "colhead" & headlayer == 1)) <-
element_entry(angle=90, hjust=0.5, vjust=0.5)
plt
Move the Outermost Layer of Row Headers Inside a Table
Description
Move the outermost layer of row headers inside
a table, by dividing
table rows into groups, with one group per level of the header. A table
row is inserted above each group, containing the value of the header for
that level as a label. This is an internal function, not intended to be
called by package users.
Usage
rowhead_inside(x, paste_rhiLabel)
Arguments
x |
A |
paste_rhiLabel |
Logical scalar. If TRUE the rowheadLabel for the outermost row header layer is prefixed to its levels when creating the interior labels. |
Details
This function changes the expanded row-column grid of the table, so must be called early in processing, before table blocks or hvrules are created.
The first column of row headers (containing the outermost row header
layer) is removed. The entries for that layer are moved to new rows
inserted into the table, so instead of appearing at the left side of the
table, they appear as labels (spanning all columns of the table) above
groups of rows. The id
, part
, subpart
,
level_in_layer
, text
, type
, and enabled
values
for those entries do not change. However headlayer
is now set to 0
(since the header is now interleaved with the body of the table),
multirow
to FALSE, and multicolumn
to TRUE (if the table has
more than one column).
The textspec
values of the moved entries may change if
paste_rhiLabel
is TRUE; an error will be raised if pasting of
markdown and non-markdown text is attempted.
The rowheadLabels
entry (if any) for the moved row header layer
also has its headlayer
set to 0, and is disabled.
Graphical properties for displaying the moved header entries can be set in
the usual ways. For example, an entryStyle
or props
specification for entries with part == "rowhead"
and
headlayer == 0
will apply just to row headers that have been moved
inside the table.
Value
If x
has at least one layer of row headers, an updated
tblEntries
object, and with attribute rowheadInside
set to
TRUE.
If x
has no row headers, or it already has row headers moved
inside, it is returned unchanged.
See Also
tblEntries
, undo_rowhead_inside
Convert ASCII Scientific Notation into plotmath
Form
Description
Convert numbers formatted as ASCII scientific notation (e.g., "1.2e-01")
into plotmath
form that will display the exponent as "10" with a
superscript. This is an internal function not intended to be called by
package users.
Usage
sci_fmt_pm(x)
Arguments
x |
A character vector. Each element should contain text representing a single number. Those elements for which the text indicates a number in scientific notation will be converted. |
Value
A character vector with the same length as x
. Any elements that
are to be treated as plotmath
expressions will begin with the
characters MATH_
See Also
textspec
Values Based on String Prefixes
Description
Return a vector of textspec
values based on special prefixes in
strings of x
. This is an internal utility function, not intended
to be called by package users.
Usage
spec_from_text(x)
Arguments
x |
Character vector. |
Details
Currently supported textspec
values and the associated prefixes
are: "plain" (no recognized prefix); "plotmath" (prefix MATH_
); and
"markdown" (prefix MKDN_
).
The returned value will be "plain" for elements of x
that are NA.
Value
Character vector with the same length as x
, containing
textspec
values. Values are determined by looking for special
prefixes in the text strings.
See Also
prefix_text
to add or remove special prefixes to text
strings based on textspec
.
Create a Style Object
Description
Create a style object that can be used to assign graphical properties to table elements (entries, hvrules, or blocks). The properties are used when displaying the elements. Styles allow assignment of graphical properties to be based on element descriptors.
Usage
styleObj(x, type, match_columns=character(0))
Arguments
x |
Data frame with (a) column(s) that specify patterns to be used to identify
and select a subset of table elements; and (b) columns specifying the
graphical properties to be used for elements in the selected subset. See
DETAILS. May also be a string with the path to a |
type |
Character string, one of "entry", "hvrule", or "block". This specifies the type of element to which the style will apply. |
match_columns |
Optional character vector (possibly empty) with the names of element
descriptors that are required in order to evaluate the subset selector
expressions in |
Details
A style specifies graphical properties to be used in displaying one of the
element types in a table (i.e., entries, hvrules, or blocks). A style is
similar to a theme in ggplot2
in that it can be applied to any
table, not just a particular table.
A styleObj
object is a data frame. Each row can be thought of as a
pattern plus a set of graphical properties. Table elements that are to be
styled are compared to the patterns. If the pattern in a style row
matches a table element, the graphical properties in that row are assigned
to the element. If more than one style row matches an element, the
properties from the last matching row override the earlier ones.
The graphical property columns that must be present in a styleObj
data frame are described in ?elements
.
Specification of style patterns and how they are matched to elements is
similar for table entries and blocks, and is described first. The process
for hvrules is more complicated and is described second. It will be
easier to follow the descriptions if one also looks at an example, such as
View(styles_pkg$entryStyle_pkg_1)
and
View(styles_pkg$hvruleStyle_pkg_1)
.
Style specification and matching: Entry and block styles
First note that table entries and blocks internally are stored in objects
that are themselves data frames, with one row per element. (These data
frames can be accessed using the elements
function.) Columns
include element descriptors such as the table part associated with the
element, its position in the table, whether the element spans multiple
rows or columns, and other information. See ?elements
for lists of
the standard descriptors.
In styles for table entries and blocks, the pattern part of the
styleObj
object consists of a single column named condition
.
condition
should contain character strings that can be interpreted
as expressions involving the element descriptors mentioned in the previous
paragraph. Each condition
expression, when evaluated within an
entries
or blocks
data frame, should produce a logical
vector with one value per element. (Vectors of length 1 are recycled to
the necessary length.) Examples of such strings are part ==
"rowhead" & multirow
for entries and type == "colblock" & subtype
== "A" & headlayer > 1
for blocks.
Elements for which the condition
expression in a style row
evaluates to TRUE are considered to match that row of the style, and are
assigned the graphical properties in that row.
An NA value (or equivalently an empty string) as a style row's
condition
is treated specially: it matches _any_ element. The
row's graphical properties will be applied to all elements, unless
overridden by a later style row.
Style specification and matching: hvrule styles
The creation and styling of hvrules is closely tied to table blocks: by default, four hvrules are created for each block, one running along each side. (They are initially disabled.) Style specification for hvrules is more complicated than for table blocks because hvrules effectively *separate* blocks. Therefore one may want their appearance to depend on characteristics of the blocks on *both* sides of the hvrule.
Similar to entries and blocks, hvrules are represented internally as a
data frame with one row per hvrule. Columns include: block
, the ID
of the block that generated the hvrule; side
, the side of
block
along which the hvrule runs ("top", "bottom", "left", or
"right"); and adjacent_blocks
, a string listing the ID's of all the
blocks adjacent to block
on the same side as the hvrule. That is,
the hvrule separates block
and the blocks in
adjacent_blocks
. Note that adjacent_blocks
may be empty.
In styles for hvrules, the pattern part of the styleObj
object
consists of three columns: block_condition
, side
, and
adjacent_condition
. side
is one of "top", "bottom", "left"
or "right". block_condition
and adjacent_condition
are like
the condition
column for block styles: they should contain
character strings that can be interpreted as expressions involving block
descriptors. Each expression will be evaluated within the data frame of
blocks that generated the hvrules. (Not the data frame containing the
hvrules themselves.) It should produce a logical vector with one element
per block; if the value is TRUE for a block, the block satisfies that
expression.
An hvrule matches a given style row if (a) its generating block satisfies
the style row's block_condition
; (b) they have the same value of
side
; and (c) one or more of the hvrule's adjacent_blocks
satisfies the style row's adjacent_condition
.
Any of block_condition
, side
, and adjacent_condition
in a style row may also be set to NA (or equivalently, to an empty
string). In that case the corresponding criterion (a), (b), or (c) is
considered to be satisfied for all hvrules, and so does not limit matches.
Note that setting adjacent_condition
to NA is the only way to
satisfy criterion (c) if an hvrule's adjacent_blocks
is empty. In
all other cases, an empty adjacent_blocks
will never satisfy
criterion (c).
Value
An object of S3 classes styleObj
and data.frame
. It will
have the same number of rows and all the columns in x
.
The object will have attributes element_type
and
match_columns
, equal to the corresponding arguments.
See Also
styles_pkg
contains predefined styles provided by the
package. They can be examined as illustrations of how styles are
specified, or edited to create new styles. elements
lists
the descriptors and graphical properties available for each element type.
Examples
# Built-in default styles:
if (interactive()) {
View(styles_pkg$entryStyle_pkg_1)
View(styles_pkg$blockStyle_pkg_1)
View(styles_pkg$hvruleStyle_pkg_1)
}
Built-In Styles for Table Elements
Description
A list that contains pre-defined styles for table entries, blocks, and hvrules. Styles are used to assign graphical properties to elements, and thus control the appearance of a table when it is displayed. In addition to the package-provided styles in this list, users can modify or create new styles to customize their tables.
Usage
styles_pkg
Format
The list has the following components, each a styleObj
object:
entryStyle_pkg_base
,blockStyle_pkg_base
,hvruleStyle_pkg_base
Minimal styles that assign the same graphical properties to all elements.
entryStyle_pkg_1
,blockStyle_pkg_1
,hvruleStyle_pkg_1
The default styles used by the package.
entryStyle_pkg_2
Similar to
entryStyle_pkg_1
, but withhpad
andvpad
about 50 percent larger, to give a more spacious layout of table entries.entryStyle_pkg_null
,blockStyle_pkg_null
,hvruleStyle_pkg_null
"Null" styles designed to not match any element, and thus not assign graphical properties to any element. Using the null style for hvrules is a way to disable all hvrules when the plot is created (rather than afterwards using a
props<-
function).
See Also
Examples
names(styles_pkg) # built-in styles
str(styles_pkg$entryStyle_pkg_1)
Summarize the Dimensions and Options of a Plotted Table
Description
Summarize the dimensions and display options of a plotted table.
Usage
## S3 method for class 'pltdTable'
summary(object, ...)
Arguments
object |
A |
... |
Additional arguments, ignored with a warning. (Included for compatibility with the generic.) |
Details
There is a print method for objects of the returned class.
Value
An object of S3 class summary.pltdTable
. It is a list with
components
adim |
Dimensions of the augmented row-column grid for the table. See
|
parts |
Data frame with one row for each table part, giving the dimensions of the
part, in columns |
mergeRuns , rowheadInside , rowgroupSize , scale , plot.margin , sizeAdjust |
Display options used by the table. See |
See Also
Examples
ttbl <- textTable(iris2_tab, title="Summary statistics for the iris data")
plt <- plot(ttbl, rowheadInside=TRUE)
summary(plt)
Summarize the Dimensions of a Table and Its Parts
Description
Summarize the dimensions of a table and its parts.
Usage
## S3 method for class 'textTable'
summary(object, ...)
Arguments
object |
A |
... |
Additional arguments, ignored with a warning. (Included for compatibility with the generic.) |
Details
There is a print method for objects of the returned class.
Value
An object of S3 class summary.textTable
. It is a list with
components
adim |
Dimensions of the augmented row-column grid for the table. See
|
parts |
Data frame with one row for each table part, giving the dimensions of the
part, in columns |
See Also
Examples
ttbl <- textTable(iris2_tab, title="Summary statistics for the iris data")
summary(ttbl)
Get or Reset Package Options
Description
Get the values of package options, or reset all options to their "factory-fresh" defaults.
Usage
tablesggOpt(x=NULL, reset=FALSE)
Arguments
x |
Character string with the name of a single package option, or NULL. |
reset |
Logical scalar. If TRUE, all options will be reset to their initial, "factory-fresh" values. |
Details
The user can change option values using the tablesggSetOpt
function. The new values will stay in effect for the rest of the R
session or until they are changed again by the user.
Value
If x
is the name of a single package option, the value of that
option. Otherwise, a named list with the current values of all package
options. In both cases the result is after resetting if reset
is
TRUE.
The result is invisible if reset
is TRUE.
The available options are documented in ?tablesggSetOpt
.
See Also
Examples
# See names of available options:
names(tablesggOpt())
# The current value of option 'plot.margin':
tablesggOpt("plot.margin")
Set the Values of Package Options
Description
Set the values of package options.
Usage
tablesggSetOpt(...)
Arguments
... |
Arguments in |
Details
The new option values persist until the end of the R session or until they
are changed by another call to this function or to
tablesggOpt(reset=TRUE)
.
The options that may be set are:
- entryStyle
A
styleObj
object, with element typeentry
. This is the default style for table entries.- blockStyle
A
styleObj
object, with element typeblock
. This is the default style for blocks.- hvruleStyle
A
styleObj
object, with element typehvrule
. This is the default style for hvrules.- plot.margin
A numeric vector of length 4, containing the amount of empty space to add around the four sides of a plotted table, in millimeters. The order of sides is top, right, bottom, left.
- allowMarkdown
Logical scalar. If TRUE then text for table entries is allowed to contain markdown and HTML tags to control its appearance. TRUE is valid only if package
ggtext
is available.- allowWrap
Logical scalar. If TRUE then automatic wrapping of text for table entries is allowed. TRUE is valid only if packages
ggtext
andquadprog
are available.
Facilities to handle markdown and automatic wrapping of entry text are
provided by Claus Wilke's ggtext
package
(https://CRAN.R-project.org/package=ggtext). Therefore
allowMarkdown
and allowWrap
can be set to TRUE only when
that package has been installed. Note that only a subset of HTML tags are
available.
Value
A list with the old values of the named options, invisibly.
See Also
tablesggOpt
to get current values of options, or to reset
options to their "factory-fresh" setting. styles_pkg
for
the set of package-provided table styles.
Examples
oldopt <- tablesggOpt()
tablesggOpt(reset=TRUE)
plt1 <- plot(iris2_tab, title="Factory-fresh default styles")
# Set new default style for table entries:
tablesggSetOpt(entryStyle=styles_pkg$entryStyle_pkg_2)
plt2 <- plot(iris2_tab, title="Changed default entry style")
# Compare:
print(plt1, vpy=0.75)
print(plt2, vpy=0.25, newpage=FALSE)
# Change the values of multiple options:
tablesggSetOpt(list(hvruleStyle=styles_pkg$hvruleStyle_pkg_base,
plot.margin=c(5, 5, 5, 5)))
# ... plot some tables using the new defaults ...
# Restore the old options:
tablesggSetOpt(oldopt)
identical(tablesggOpt(), oldopt)
Define Blocks of Cells that Reflect the Logical Structure of a Table
Description
Define a collection of rectangular blocks of cells that reflect the logical structure of a table. This is an internal function, not intended to be called by package users.
Usage
tblBlocks(x, rowgroupSize=0, ...)
Arguments
x |
A |
rowgroupSize |
Numeric scalar. If greater than 0, blocks will be created by grouping consecutive rows of the table body into sets of this size. See DETAILS. |
... |
Additional arguments passed to |
Details
A block is simply a rectangular set of contiguous table cells. Any number
of blocks may be defined for a given table, and blocks may overlap. A
block may be empty (nr
and/or nc
equal to 0, and
corresponding arow*
and acol*
values set to NA.)
This function defines a standard set of blocks based on the logical structure of a table (but independent of the _content_ of table cells). The following blocks are defined:
"table" : The whole table (all cells). "title", "subtitle", "colhead",
"rowhead", "rowheadLabels", "body", "foot" : The standard table parts.
(If there are interior row header entries, rowhead
and body
are omitted because the interleaving of headers and body means neither are
valid blocks.) "titles" : The union of the title
and
subtitle
parts. "stub" : If we exclude the title/subtitle and foot
annotations, a table has four quadrants: the body at the lower right, the
row headers at the lower left, the column headers at the upper right, and
a stub at the upper left. That is, the stub consists of the cells above
the row headers and to the left of the column headers. (If there are row
header labels–block rowheadLabels
–they will be in the bottom row
of the stub.) "colhead_and_stub", "rowhead_and_stub" : The unions of
stub
with colhead
and rowhead
, respectively.
"colhead_and_body", "rowhead_and_body" : The unions of body
with
colhead
and rowhead
, respectively.
Each of these blocks is unique and so their id
and type
are
the same string. subtype
, headlayer
, and
level_in_layer
are set to NA for them.
Blocks representing the hierarchical structure of headers
Additional blocks, with types "rowblock" and "colblock", are defined to represent the hierarchical structure of row and column headers. To describe these blocks, some terminology is needed. For concreteness, the description is in terms of column headers; analogous comments apply to row headers.
When a table is displayed, each _row_ of column headers (corresponding to
a row of the colhead
matrix in a textTable
object), defines
one _layer_ of the header. Layers are numbered from innermost (closest to
the table body) to outermost. Structurally, layers form a hierarchy:
header values at a lower numbered (inner) layer are nested within values
at higher numbered (outer) layers. This hierarchy implies a
tree-structured partitioning of table columns according to values of the
header variables. A set of contiguous columns that share the same header
value for a layer, and for all layers above it in the hierarchy, belong to
a single _level_ of that layer. Levels are numbered from 1 to the number
of levels in a layer.
Then for each combination of layer number i
and level number
j
in a header, three blocks are defined. A block with subtype "A"
consists of just the cells in header layer i
whose value
corresponds to level number j
. It will thus come from a single row
in the column headers of the table. And since all the cells in the block
have the same value, those cells will typically be merged into a single
entry when displaying the table.
A block with subtype "B" is bigger: it consists of the cells in the
subtype "A" block, plus the header cells with _smaller_ layer numbers in
the same columns. So it extends from layer i
down through the rest
of the header rows. And finally a block with subtype "C" is bigger yet:
it consists of the cells in the subtype "B" block plus the cells in the
table body in the same columns. That is, it spans the same set of columns
as the subtype "A" and "B" blocks but adds rows down through the table
body. Block ID's have the form colblock/<subtype>/i/j
.
Sets of blocks for the row headers are defined analogously. Each _column_
in the row headers of a displayed table (corresponding to a column in the
rowhead
matrix of a textTable
object) represents one layer.
The layer closest to the table body is numbered 1 and layer number
increases toward the left edge of the table. A subtype "A" block consists
of the cells in layer number i
whose value corresponds to level
number j
in that layer. It will thus come from a single column in
the row headers of the table. A subtype "B" block consists of the cells
in the "A" block, plus the header cells with _smaller_ layer numbers in
the same rows. A subtype "C" block further adds the cells in the table
body in the same rows. That is, it spans the same set of rows as "A" and
"B" blocks but adds columns across through the table body. Block ID's
have the form rowblock/<subtype>/i/j
.
Blocks when rowheadInside
is TRUE
Moving the outermost layer of row header entries into the interior of the
table, where they separate and label groups of rows, changes the shape of
table parts. Specifically, since row headers and body are interleaved,
neither forms a valid rectangular block. However their union is a valid
block, with ID and type rowhead_and_body
.
When a row header layer is moved inside, its layer number is set to 0.
(Conceptually, since it is interleaved with the table body, it is interior
even to header layer 1.) Blocks rowblock/<subtype>/i/j
, where
i
indicates layer number, are different when i=0 than for other
layers. Subtype "A", rowblock/A/0/j
, has one row and spans all
table columns. It contains the label for the j
-th level. Subtype
"B", rowblock/B/0/j
, contains all row header entries (if any)
nested within level j
. Subtype "C", rowblock/C/0/j
,
combines rowblock/B/0/j
with all the body rows associated with
level j
. Thus rowblock/C/0/j
spans all table columns.
Unlike when i
is not equal to 0, neither rowblock/B/0/j
nor
rowblock/C/0/j
contain rowblock/A/0/j
.
Blocks representing groups of rows
When a table has many rows within a given level of the row header
hierarchy, the table may be easier to read if rows are grouped into
smaller sets of fixed size (groups of 5, for example), with some extra
space inserted between groups. To facilitate this, this function creates
blocks representing such groups when rowgroupSize
is positive. The
block type is "rowblock" and subtype is "G".
Grouping respects the row header hierarchy: the innermost header layer
that has runs of repeated values is identified (layer i
say), and
grouping is done separately within each of its levels. The block
representing a row group spans all columns of the table body as well as
row header layers out to layer i-1
. Block ID's have the form
rowblock/G/i/j/k
, where j
is the level number (within layer
i
) that contains the group, and k
is the group number within
that level. Thus i
, j
, and k
are the values of
headlayer
, level_in_layer
, and group_in_level
for the
block.
However if the table has no row headers, or none of the row header layers
have runs of repeated values, table rows are simply grouped into sets of
size rowgroupSize
. headlayer
and level_in_layer
will
be NA for the group blocks, and block ID's will have the form
rowblock/G///k
, where k
is the group number (and value of
group_in_level
).
Value
An S3 object of class tblBlocks
. This is a data frame with one row
per block. It contains information about the nature and position of each
block. Column descriptions are in the documentation for the
elements
function. Also see DETAILS for more information about
columns id
, type
, and subtype
.
Row names for the data frame are set equal to id
.
rowgroupSize
and rowheadInside
(the latter taken from
x
, after converting it to a tblEntries
object if necessary)
will be included as attributes.
See Also
tblEntries
, tblParts
, elements
;
as.tblBlocks
converts a data frame to a tblBlocks
object.
Assemble Information About Each Entry in a Table into a Data Frame
Description
Assemble information about each entry in a table into a data frame with one row per entry, and columns for entry content and position in the table. This is an internal function, not intended to be called by package users.
Usage
tblEntries(x, mergeRuns=c(TRUE, TRUE), rowheadInside=FALSE)
Arguments
x |
A |
mergeRuns |
Two-element logical vector, the first element applying to row headers, the
second to column headers. If TRUE (the default) then header cells that
contain runs of the same value will be merged into a single entry that
spans multiple rows or columns. Note that runs in the outermost row
header layer are always merged when |
rowheadInside |
Logical scalar. If TRUE, the outermost layer of row headers is moved inside the table by using its levels to divide the table into groups of rows, with each group labeled by their level. |
Details
Entries include all parts of the table: the body of the table, row and
column headers, titles, subtitles, and foot lines. This function calls
textTable(x)
to convert table entries to character strings if
necessary.
If the text for an entry is missing (NA) the entry will be disabled, with a warning. If the text is an empty string (""), the entry will be disabled by default; this is so that blocks containing only empty cells will not have hvrules generated for them.
Row and column numbers used in creating default entry ID's are
partrow
and partcol
, and thus with respect to the dimensions
of the table part the entry belongs to, not the augmented row-column grid.
If an entry spans more than one row or column, the minimum row/column
number of the spanned cells is used.
The rowhier
and colhier
attributes are included primarily to
assist creation of table blocks by function tblBlocks
.
The inclusion of the hjust
column is not tidy, since it is really a
graphical display property. However it is needed to carry forward
justification information that x
may have inherited from a
tabular
object.
The tblEntries
method for textTable
is the inverse of this
function: it will re-create a textTable
from a tblEntries
object.
Value
An object of S3 class tblEntries
. This is a data frame with one
row per entry in the table. It contains descriptors with information
about the nature and position of each entry within the table. Column
descriptions are in the documentation for the elements
function.
Additional details for certain columns are:
subpart |
For row and column headers, the subpart will be the name of the
corresponding column in |
level_in_layer |
Numbering of entries within a given part and headlayer. For row and
column headers this is based their hierarchical structure (see
|
type |
Character string identifying the type of value the entry represents (e.g.,
"numeric"). This is taken from the |
textspec |
Character string indicating any special features of the text in
|
enabled |
Logical indicating whether the entry is to be displayed. This function
sets |
hjust |
Numeric horizontal justification specification for entry text (0=left,
0.5=center, 1=right, NA=unspecified). This is set based on the
|
Row names for the data frame are set equal to id
. The data frame
has attributes mergeRuns
and rowheadInside
, based on the
arguments. It also has attributes rowhier
and colhier
,
containing information about the row and column header hierarchies. They
are lists of data frames, copied from the corresponding components of
x
. They reflect the logical structure of the headers and are
unaffected by display choices such as mergeRuns
and
rowheadInside
.
See Also
textTable
, tblParts
;
as.tblEntries
, elements
.
Create Horizontal and Vertical Rules for a Table
Description
Create horizontal and vertical rules (hvrules) for a table, based on blocks of table entries. This is an internal utility function, not intended to be called directly by package users.
Usage
tblHvrules(x)
Arguments
x |
A |
Details
This function creates four hvrules per block: two hrules that run along the top and bottom sides of the block, and two vrules that run along the left and right sides of the block. All of the generated hvrules are disabled by default.
No graphical properties of the hvrules, such as the size of the inserted
rectangle or the appearance of the line within it, are assigned by this
function. hvrules can be selectively enabled and given graphical
properties by applying a style (see styleObj
) to create plot-ready
hvrules (a prHvrule
object). Properties in an existing plot can
also be modified using the props<-
function.
Value
An object of S3 class tblHvrules
, which is a data frame with each
row specifying one hvrule for the table. If there are no hvrules, the
data frame will have no rows. Columns are:
id |
A unique identifier for the hvrule. This function creates identifiers
using the format |
direction |
Either "hrule" for a horizontal rule or "vrule" for a vertical rule. |
block |
The identifier of the block along the side of which the hvrule runs. |
side |
Which side of the block the hvrule runs along, "top", "bottom", "left", or "right". |
adjacent_blocks |
Character string containing the IDs of blocks that are adjacent to
|
arow1 , arow2 , acol1 , acol2 |
Location of the hvrule with respect to the expanded row-column grid of the
table. An hrule is inserted between table rows, and therefore
|
enabled |
Logical indicating whether the hvrule is to be displayed. This function
sets |
Row names for the data frame are set equal to id
.
See Also
tblBlocks
defines a default set of blocks that reflect the
logical structure of the table. This function is called by internal
function apply_style
.
Extract Dimensions of the Various Parts of a Table
Description
Extract information about the dimensions of the various parts of a table
represented by a textTable
or tblEntries
object. This is an
internal function not intended to be called by package users.
Usage
tblParts(x)
Arguments
x |
A |
Details
Currently defined table parts are "title", "subtitle", "rowhead", "colhead", "rowheadLabels", "body", "foot".
The dimensions of a part are based on the logical structure of the table,
as represented in a textTable
object. When x
is a
tblEntries
or other entry-containing object, the dimensions of
table parts are inferred from the numbers and positions of entries in each
part. It is an error if the set of entries is not sufficiently complete
that reconstruction of dimensions is unambiguous.
When inferring dimensions from a tblEntries
or other
entry-containing object, the display option rowheadInside
is
implicitly set to FALSE. Thus table parts can be assumed to be
rectangular, occupying continguous blocks of cells in the table, and
non-overlapping.
Internal consistency of dimensions is enforced: the number of rows for "colhead" will always be at least as large as for "rowheadLabels"; the number of columns for "rowheadLabels" and "rowhead" will be equal; the number of rows in "rowhead" and "body" will be equal; and the number of columns in "colhead" and "body" will be equal.
This function relies on undo_rowhead_inside
, which uses
adim
.
Value
Numeric matrix with one row per table part, and columns:
nr , nc |
Number of rows, columns in the part ( |
arow1 , arow2 , acol1 , acol2 |
First and last rows, first and last columns occupied by the part within
the table's augmented row-column grid. |
Row names will be set to the part IDs.
See Also
adim
for discussion of the augmented row-column grid.
Create a Structure Representing a 2D Table
Description
Create a structure representing the content and organization of a 2D table: table body, row and column headers, and annotation. All table cells are formatted as character strings. This is an S3 generic.
Usage
textTable(x, ...)
Arguments
x |
Object to be formatted as a 2D table. |
... |
Additional arguments passed to specific methods. |
Details
textTable
objects are the fundamental structure used to represent
table _content_ and _organization_ in the tablesgg
package.
Components body
, rowhead
, rowheadLabels
,
colhead
, title
, subtitle
, and foot
correspond
to the table _parts_ with those names. Empty parts should be of type
character: either a 0-length vector or a matrix with one or both
dimensions equal to 0, depending on the component.
Character strings representing table content may be prefixed with either
"MATH_" or "MKDN_". The former indicates the string is to be interpreted
as a plotmath
expression, the latter that the string contains
markdown or HTML tags.
Components partdim
, rowhier
, and colhier
are
automatically derived from the other components whenever a
textTable
is created or updated.
See Appendix A of the package vignette for more information about writing
textTable
methods.
Value
An object with S3 class textTable
. This is a list with components:
body |
Character matrix containing the body of the table. |
rowhead |
Character matrix with the same number of rows as the table body, containing row headers for the table. Row headers are displayed as a set of columns to the left of the table body. May be empty (0 columns). |
rowheadLabels |
Character matrix with as many columns as |
colhead |
Character matrix with the same number of columns as the table body,
containing column headers for the table. Column headers are displayed as
a set of rows above the table body. If |
title , subtitle , foot |
Character vectors providing annotation for the table. May be empty (length 0). |
partdim |
Numeric matrix with one row per table part (i.e., the components listed above), and columns:
|
rowhier , colhier |
Lists describing the hierarchical structure of row and column headers,
respectively. Each list has one component per header layer (column of
|
Components body
, rowhead
, and colhead
will each have
an attribute type
. For body
this will be a character matrix
with the same dimensions, containing an arbitrary string describing the
type of value represented in each cell (e.g., "numeric"), or NA. For
rowhead
and colhead
, it will be a character vector with
length equal to the number of layers of headers (i.e., number of columns
in rowhead
, number of rows in colhead
), again containing a
string describing the type of values in each layer, or NA.
Components body
, rowhead
, rowheadLabels
,
colhead
, title
, subtitle
, and foot
will each
have an attribute justification
. It will be a character matrix or
vector of the same size and shape as the component. Values "l", "c", "r"
specify left, centered, and right horizontal justification of text,
respectively, for the corresponding table entry. Value NA means that the
type of justification is not specified–it will be set by the entry style
used when plotting the table.
See Also
Specific methods for creating textTable's from other objects.
Create a texttable
as a Simple Listing of a Data Frame
Description
Create a textTable
object representing a simple listing of a data
frame.
Usage
## S3 method for class 'data.frame'
textTable(x, title=character(0), subtitle=character(0),
foot=character(0), row.names="", na="NA", ...)
Arguments
x |
A data frame. |
title , subtitle , foot |
Optional character vectors providing annotation for the table. May be
empty (i.e., |
row.names |
A logical scalar or a character string. If FALSE, the row names of
|
na |
Character string used to represent missing values (NAs) in the body of the table. |
... |
Additional arguments passed to |
Details
This function processes a data frame into a table that is simply a listing
of the data. There is one row in the body of the table per observation in
x
, and one column per variable in x
. There is at most one
layer of row headers (depending on argument row.names
), and exactly
one layer of column headers (the variable names in x
).
Value
An object with S3 class textTable
. The body of the table will
contain the values of the data frame variables, after formatting x
with format(x, ...)
. The variable names will be used as the column
header, and if row.names
is not FALSE, the row names will form the
row header.
Examples
data(iris, package="datasets")
ttbl <- textTable(head(iris, 10), row.names="Obs. #",
title=c("The iris data", "(First 10 observations)"))
summary(ttbl)
plot(ttbl)
Create a texttable
Object from a Suitable List
Description
Create a textTable
object from a list with one component per table
part, with validity checking. Components partdim
, rowhier
,
colhier
are added/re-derived from the table parts. Missing
type
and justification
attributes are added. Components are
put in standard order. This is an internal function not intended to be
called by package users.
Usage
## Default S3 method:
textTable(x, ...)
Arguments
x |
A list with components for each of the table parts. See |
... |
Ignored, with a warning. (Present for compatibility with the generic.) |
Details
Methods to create a textTable
from other object classes should
generally finish by calling this function. It will do validity checking
and fill in or update the necessary components and attributes.
Value
An object with S3 class textTable
. Table parts will be in standard
order: "title", "subtitle", "rowhead", "rowheadLabels", "colhead", "body",
"foot".
See Also
textTable
for documentation about the class.
Create a texttable
from an ftable
Description
Create a textTable
object representing a flattened multiway
contingency table.
Usage
## S3 method for class 'ftable'
textTable(x, colheadLabels=c("layers", "none", "paste"), sep=": ",
title=character(0), subtitle=character(0), foot=character(0), ...)
Arguments
x |
An |
colheadLabels |
Character scalar; how to display names of column header variables. "none"
means to not display them. "layers" (the default) means to display them
as additional column header layers (so each header variable occupies two
rows instead of one). "paste" means to paste the variable name in front
of each of its values, separated by |
sep |
Character scalar; string that separates a variable name from its values
when |
title , subtitle , foot |
Optional character vectors providing annotation for the table. May be
empty (i.e., |
... |
Ignored, with a warning. (Included for compatibility with the generic.) |
Value
An object with S3 class textTable
. See the documentation for the
generic for details about its structure.
See Also
ftable
, format.ftable
Examples
# From examples in '?ftable':
data(Titanic, package="datasets")
ft <- ftable(Titanic, row.vars = 1:2, col.vars = "Survived")
ttbl <- textTable(ft, title="Plotting an 'ftable'")
plot(ttbl)
data(mtcars, package="datasets")
ft <- ftable(mtcars$cyl, mtcars$vs, mtcars$am, mtcars$gear, row.vars = c(2, 4),
dnn = c("Cylinders", "V/S", "Transmission", "Gears"))
ttbl <- textTable(ft, colheadLabels="none")
plt1 <- plot(ttbl, title="Plotting an 'ftable'",
subtitle="No colheadLabels")
ttbl <- textTable(ft, colheadLabels="layers")
plt2 <- plot(ttbl, title="Plotting an 'ftable'",
subtitle="colheadLabels = 'layers'")
ttbl <- textTable(ft, colheadLabels="paste")
plt3 <- plot(ttbl, title="Plotting an 'ftable'",
subtitle="colheadLabels = 'paste'")
print(plt1, position=c("left", "top"))
print(plt2, position=c("left", "center"), newpage=FALSE)
print(plt3, position=c("left", "bottom"), newpage=FALSE)
Create a texttable
from a Matrix
Description
Create a textTable
object from a matrix.
Usage
## S3 method for class 'matrix'
textTable(x, rcnames=c(TRUE, TRUE), title=character(0),
subtitle=character(0), foot=character(0), na="NA", ...)
Arguments
x |
A matrix. |
rcnames |
A logical or character vector of length 2. The first element applies to
rows, the second to columns. If FALSE, row/column names are not included.
If TRUE and |
title , subtitle , foot |
Optional character vectors providing annotation for the table. May be
empty (i.e., |
na |
Character string used to represent missing values (NAs) in the body of the table. |
... |
Additional arguments passed to |
Value
An object with S3 class textTable
. The body of the table will
contain the matrix values, after formatting x
with format(x,
...)
. Row and column names may be included as headers, depending on
argument rcnames
.
Examples
data(iris, package="datasets")
mat <- data.matrix(subset(iris, Species == "setosa")[, 1:4])
ttbl <- textTable(cor(mat), digits=3, title="Correlations for setosa irises")
summary(ttbl)
plt <- plot(ttbl)
# Make hvrules invisible:
propsd(plt, subset=enabled) <- element_hvrule(color=NA)
print(plt)
Create a texttable
from a table
or xtabs
Object
Description
Create a textTable
object representing a flattened multiway
contingency table.
Usage
## S3 method for class 'table'
textTable(x, colheadLabels=c("layers", "none", "paste"), sep=": ",
title=character(0), subtitle=character(0), foot=character(0), ...)
Arguments
x |
A |
colheadLabels |
Character scalar; how to display names of column header variables. "none"
means to not display them. "layers" (the default) means to display them
as additional column header layers (so each header variable occupies two
rows instead of one). "paste" means to paste the variable name in front
of each of its values, separated by |
sep |
Character scalar; string that separates a variable name from its values
when |
title , subtitle , foot |
Optional character vectors providing annotation for the table. May be
empty (i.e., |
... |
Additional arguments passed to |
Details
This function simply converts x
to an ftable
(flattened
multiway contingency table), then applies the corresponding
textTable
method to that object.
It also works for xtabs
objects since they inherit from
table
.
Value
An object with S3 class textTable
. See the documentation for the
generic for details about its structure.
See Also
ftable
, xtabs
Examples
# UCBAdmissions is a contingency table in array form ('table' object).
data(UCBAdmissions, package="datasets")
ttbl <- textTable(UCBAdmissions)
plot(ttbl, title=c("Plotting a 'table' object:", "UCB Admissions data"))
# Method also works for 'xtabs' since they inherit from 'table' (example
# from '?xtabs'):
data(warpbreaks, package="datasets")
warpbreaks$replicate <- rep_len(1:9, 54)
xt <- xtabs(breaks ~ wool + tension + replicate, data = warpbreaks)
ttbl <- textTable(xt, title="Plotting an 'xtabs' object (warpbreaks data)")
plot(ttbl)
Create a texttable
from a tabular
Object
Description
Convert a tabular
object, representing a 2D data summary table,
into a textTable
object, which can be plotted.
Usage
## S3 method for class 'tabular'
textTable(x, title=character(0), subtitle=character(0),
foot=character(0), rowheadLabels=TRUE, ...)
Arguments
x |
An object of class |
title , subtitle , foot |
Optional character vectors providing annotation for the table. May be
empty (i.e., |
rowheadLabels |
Character vector or logical scalar specifying labels for the row header
columns of the table. FALSE or |
... |
Additional arguments passed to |
Details
tabular
objects are produced by the tabular
function in
package tables
. This function converts them to textTable
objects to enable plotting. It can also add table annotation.
Row headers and column headers are derived from the rowLabels
and
colLabels
attributes of x
, respectively. It appears that
tabular
objects always have "rowLabels", "colLabels" and a body
with non-zero dimensions (although this is not required for
textTable
objects in general). In addition, runs of duplicated
values in rowLabels
and colLabels
are replaced by NA; the
NAs are changed back to the original values by this function. The
dropcells
attribute is a character matrix matching the table body.
If not NA, the value in dropcells
is used to replace the cell
content after formatting.
In the returned object, components body
, rowhead
, and
colhead
will each have an attribute type
. For body
the attribute is a character matrix containing a string describing the
type of value represented in each cell of the table body; namely, the
first element of the vector returned by function class()
as applied
to each element of x
. For rowhead
and colhead
,
type
is a character vector with one element per header variable
(i.e., per column of rowhead
or row of colhead
). Since
tabular
objects do not retain the classes of the variables that
define row and column dimensions of a table, type
will be set to
NA.
Components of the returned object will also have an attribute
justification
. It will be a character matrix or vector of the same
size and shape as the component; a value of NA means that the type of
justification is not specified. Values for the table body and row and
column headers will be taken from x
. Values for table annotation
will be NA.
Value
An object with S3 class textTable
. See the documentation for the
generic function for a description of the structure of this object.
See Also
tables::tabular
, tables::format.tabular
,
plot.textTable
Examples
# 'iris2_tab' is a 'tabular' object created using 'tables::tabular'.
class(iris2_tab)
# 'tables' package provides a 'print' method for such objects:
if (requireNamespace("tables", quietly=TRUE)) {
print(iris2_tab)
}
# This package provides 'textTable' and 'plot' methods for such objects:
ttbl <- textTable(iris2_tab)
plot(ttbl)
# ... or just
#plot(iris2_tab) # same
Reconstruct a texttable
Object from a tblentries
Object
Description
Reconstruct a textTable
object from a tblEntries
object.
This is an internal utility function, not intended to be called by package
users.
Usage
## S3 method for class 'tblEntries'
textTable(x, ...)
Arguments
x |
A |
... |
Ignored, with a warning. (Present for compatibility with the generic.) |
Value
A textTable
object.
See Also
Create a texttable
from an xtable
Object
Description
Create a textTable
from an xtable
object produced by the
xtable
package. The textTable
can then be styled and
plotted.
Usage
## S3 method for class 'xtable'
textTable(x, title, subtitle=character(0), foot=character(0),
row.names="", na="", mathExponents=TRUE, ...)
Arguments
x |
An |
title |
Optional character vector containing title lines for the table. May be
empty ( |
subtitle , foot |
Optional character vectors providing additional annotation for the table.
May be empty (i.e., |
row.names |
A logical scalar or a character string. If FALSE, the row names of
|
na |
String to be used to represent missing values in |
mathExponents |
Logical scalar. If TRUE, then numerical values in |
... |
Additional named arguments passed to |
Details
This function was designed based on the structure of objects produced by
version 1.8-4 of the xtable
package.
An xtable
object is a data frame that contains the columns of the
table and attributes that specify how those columns are to be formatted.
This function uses those attributes to created formatted character strings
for each table entry, and assembles them into a textTable
object,
which may then be styled and plotted.
Formatting is done by formatC
using the digits
and
display
attributes of x
. The align
attribute is used
to set the justification
attributes in the returned
textTable
. (Vertical rule characters, |
, within
align
are ignored; use an hvruleStyle
or the
addHvrule
function to insert vertical rules into the plotted table,
as shown in the examples.)
Value
An object with S3 class textTable
. See the documentation for the
generic for details about its structure.
Examples
# 'tli_xtab' is an 'xtable' object created using 'xtable::xtable':
class(tli_xtab)
# This package provides a 'textTable' method for such objects:
ttbl <- textTable(tli_xtab)
plot(ttbl)
if (requireNamespace("xtable", quietly=TRUE)) withAutoprint({
data(tli, package="xtable")
# ANOVA table.
fm1 <- aov(tlimth ~ sex + ethnicty + grade + disadvg, data = tli)
plt1 <- plot(textTable(fm1.table <- xtable::xtable(fm1),
title="xtable: ANOVA table"))
# Table of linear regression results.
fm2 <- lm(tlimth ~ sex*ethnicty, data = tli)
plt2 <- plot(textTable(fm2.table <- xtable::xtable(fm2),
title="xtable: Linear regression"))
# Time series table.
temp.ts <- ts(cumsum(1 + round(rnorm(100), 0)), start = c(1954, 7),
frequency = 12)
plt3 <- plot(textTable(xtable::xtable(temp.ts, digits = 0),
title="xtable: Time series"))
# Math style for scientific notation.
plt4 <- plot(textTable(xtable::xtable(data.frame(text = c("foo","bar"),
googols = c(10e10,50e10),
small = c(8e-24,7e-5),
row.names = c("A","B")),
display = c("s","s","g","g")),
mathExponents = TRUE,
title=c("xtable:", "Math style for scientific notation")))
print(plt1, position=c(0.1, 0.9))
print(plt2, position=c(0.1, 0.5), newpage=FALSE)
print(plt3, position=c(0.1, 0.1), newpage=FALSE)
print(plt4, position=c(0.9, 0.9), newpage=FALSE)
# By default vertical rules specified by '|' characters in 'align' are
# ignored. They can be added afterward using the 'addHvrule' function
# as follows:
tli.table <- xtable::xtable(tli[1:10, ])
xtable::align(tli.table) <- "|rrl|l|lr|"
plt <- plot(textTable(tli.table,
title="xtable: Vertical rules derived from 'align'"))
pipe_posn <- which(unlist(strsplit(attr(tli.table, "align"), "")) == "|")
vrule_acol <- pipe_posn - seq_along(pipe_posn) + 0.5
for (ac in vrule_acol) plt <- addHvrule(plt, direction="vrule", acols=ac,
arows=arow(plt, "colhead_and_body"),
props=element_hvrule(linetype=1,
color="black"))
plt
})
Create a texttable
from an xtablelist
Object
Description
Create a textTable
from an xtableList
object produced by the
xtable
package. Such an object represents a set of subtables that
are to be stacked into a single table, with "subheadings" separating the
subtables. The textTable
that is produced by this function uses
the subheadings as an additional, outer row header layer. That layer can
optionally be moved inside the table by setting rowheadInside=TRUE
when the table is plotted.
Usage
## S3 method for class 'xtableList'
textTable(x, title, subtitle=character(0), foot, ...)
Arguments
x |
An |
title |
Optional character vector containing title lines for the table. May be
empty ( |
subtitle , foot |
Optional character vectors providing additional annotation for the table.
May be empty (i.e., |
... |
Additional arguments passed to |
Details
This function was designed based on the structure of objects produced by
version 1.8-4 of the xtable
package.
If x
has a message
attribute, it is used as the default
value of the foot
component of the returned textTable
.
If components of x
have no subheading
attribute, then the
subtables are simply stacked, with no additional row header layer to
separate or distinguish them. It is an error if only some of the
components have a subheading
attribute.
Value
An object with S3 class textTable
. See the documentation for the
generic for details about its structure.
Examples
# 'mtcars_xtab' is an 'xtableList', following an example in the
# "listOfTablesGallery" vignette of the 'xtable' package. (See '?mtcars_xtab'
# for the code to create it.)
plot(textTable(mtcars_xtab), rowheadInside=TRUE,
title="Example of plotting an 'xtableList'",
subtitle="(With 'rowheadInside=TRUE')")
Table of Test Scores and Demographics for 20 Students
Description
This is a table of the first 20 observations from the data frame tli
from package xtable. The observations include demographic data and
math scores, from the Texas Assessment of Academic Skills, for 20 students.
Usage
tli_xtab
Format
An xtable
object as produced by version 1.8-4 of the xtable
package (https://CRAN.R-project.org/package=xtable
). The table was
produced with the following code:
data("tli", package="xtable") tli_xtab <- xtable::xtable(tli[1:20, ]) xtable::display(tli_xtab)[c(2,6)] <- "f" xtable::digits(tli_xtab) <- matrix(0:4, nrow = 20, ncol = ncol(tli)+1)
Source
Texas Education Agency, <URL: http://www.tea.state.tx.us>
Examples
str(tli_xtab)
Reverse the Effect of rowhead_inside
Description
Reverse the effect of rowhead_inside
for a tblEntries
object: Move row headers that are inside a table back to the outermost
layer of row headers, at the left side. This is an internal function, not
intended to be called by package users.
Usage
undo_rowhead_inside(x)
Arguments
x |
A |
Details
This function changes the expanded row-column grid of the table, so must be called early in processing, before table blocks or hvrules are created.
See rowhead_inside
for what happens when the outermost row header
is moved inside the table; this function reverses that. (However the
order of entries may be changed from the original.)
Value
An updated tblEntries
object, and with attribute
rowheadInside
set to FALSE.
See Also
Update a pltdtable
(Plotted Table) Object
Description
Update a pltdTable
(plotted table) object with new styles or
scaling.
Usage
## S3 method for class 'pltdTable'
update(object, entryStyle=NULL, blockStyle=NULL, hvruleStyle=NULL,
scale=NULL, plot.margin=attr(object, "plot.margin"),
sizeAdjust=attr(object, "sizeAdjust"), ...)
Arguments
object |
A |
entryStyle , blockStyle , hvruleStyle |
Optional |
scale |
Optional numeric multiplier used to increase or decrease the displayed
size of table elements, relative to the natural size implied by their
(possibly updated) styles. If it has length two, the first element
applies to entries and blocks, and the second to hvrules. The default is
to use the existing scale value(s) in |
plot.margin , sizeAdjust |
See the documentation for |
... |
Ignored, with a warning. (Included for compatibility with the generic.) |
Details
Updating a plotted table is limited to changing its style or
scale–changes that do not affect the augmented row-column grid of the
table. (See adim
for a description of that grid.) For other
changes, start with a textTable
object, and edit it and/or replot
it using different arguments (e.g., rowheadInside
,
rowgroupSize
, mergeRuns
, or annotation).
Updating does not change the enabled
field for any entries, blocks,
or existing hvrules.
When argument hvruleStyle
is provided, hvrules are regenerated by
applying the style to the blocks component of object
. These new
hvrules replace any existing hvrules with the same ID. However existing
hvrules with other ID's are left unchanged.
Value
An object of S3 class pltdTable
, inheriting from ggplot
.
See plot.textTable
for details about this object.
See Also
Examples
# Plot using 'factory-fresh' entry style:
plt <- plot(textTable(iris2_tab), entryStyle=styles_pkg$entryStyle_pkg_1)
# Change to a generic style that uses the same graphical properties for
# all entries:
plt2 <- update(plt, entryStyle=styles_pkg$entryStyle_pkg_base)
plt2
# Also make the plot smaller:
plt3 <- update(plt2, scale=0.8)
plt3
Update Style or Scale for Plot-Ready Table Elements
Description
Update a prEntries
, prBlocks
, or prHvrules
object
with a new style and/or new scale. This is an internal utility function,
not intended to be called directly by package users.
Usage
## S3 method for class 'prObj'
update(object, style=NULL, scale=NULL, ...)
Arguments
object |
A |
style |
Optional |
scale |
Optional numeric multiplier used to increase or decrease the displayed
size of table elements, relative to the natural size implied by the
(possibly updated) style. The default is to use the current scaling of
|
... |
Ignored, with a warning. (Included for compatibility with the generic.) |
Details
The enabled
field is not changed for any elements. (Changing
enabled
for entries could have cascading effects on blocks and
hvrules.)
To provide a mechanism to hold graphical properties fixed for certain
elements, style
is not applied to any elements for which
style_row
is 0. This will be true for elements created manually
via addBlock
or addHvrule
for example. Graphical properties
for such elements can be changed using props<-
.
The style of a prHvrules
object cannot be updated directly, because
the object does not contain the block information generally needed to
apply styles. Instead, a new set of hvrules should be created from a
tblBlocks
object with the desired style, using function
prHvrules
.
Value
An object with the same class as object
. See prEntries
,
prBlocks
, or prHvrules
for the structure of these objects.
See Also
Update a prtable
(Plot-Ready Table) Object
Description
Update a prTable
object with new entry, block, or hvrule styles,
and/or new scale. This is an internal utility function, not intended to
be called directly by package users.
Usage
## S3 method for class 'prTable'
update(object, entryStyle=NULL, blockStyle=NULL, hvruleStyle=NULL,
scale=NULL, ...)
Arguments
object |
A |
entryStyle , blockStyle , hvruleStyle |
Optional |
scale |
Optional numeric multiplier used to increase or decrease the displayed
size of table elements, relative to the natural size implied by their
(possibly updated) styles. If it has length two, the first element
applies to entries and blocks, and the second to hvrules. The default is
to use the existing scale value(s) in |
... |
Ignored, with a warning. (Included for compatibility with the generic.) |
Details
The enabled
field is not changed for any entries, blocks, or
existing hvrules. (Changing enabled
for entries could have
cascading effects on blocks and hvrules.)
When argument hvruleStyle
is provided, hvrules are regenerated by
applying the style to the blocks
component of object
. These
new hvrules replace any existing hvrules with the same ID. However
existing hvrules with other ID's are left unchanged.
Users should generally update pltdTable
objects, not prTable
objects.
Value
An object of S3 class prTable
, a plot-ready table. See
prTable.prEntries
for the structure of this object.
See Also
Update a texttable
Object
Description
Update a textTable
object with new annotation or rowheadLabels.
Usage
## S3 method for class 'textTable'
update(object, title=NULL, subtitle=NULL, foot=NULL,
rowheadLabels=NULL, ...)
Arguments
object |
A |
title , subtitle , foot |
Optional character vectors of annotation for the table. NULL means to
leave the current annotation unchanged (the default); |
rowheadLabels |
Optional character vector or 1-row matrix specifying labels for the row
header columns of the table. NULL means to leave the current value
unchanged (the default); |
... |
Ignored, with a warning. (Present for compatibility with the generic.) |
Details
To indicate that a string in title
, subtitle
, foot
,
or rowheadLabels
is to be interpreted as a plotmath
expression, prefix it with MATH_
. To indicate that it contains
markdown or HTML tags, prefix it with MKDN_
.
Value
A textTable
object with annotation set or changed based on the
provided arguments.
See Also
Examples
ttbl <- textTable(iris2_tab, title="The iris data",
foot="sd = standard deviation")
# Change annotation:
ttbl <- update(ttbl, title=c("The iris data", "Summary statistics by species"),
foot=character(0))
plot(ttbl)
# Change row header labels:
ttbl <- update(ttbl, rowheadLabels=c("Species", "Summary\nstatistic"))
plot(ttbl)