The BasicTable class represents a table with styling and formatting that can be rendered to multiple output formats.

## Format

R6Class object.

## Active bindings

argumentCheckMode

The level of argument checking to perform. One of "auto", "none", "minimal", "basic", "balanced" (default) or "full".

compatibility

A list containing compatibility options to force legacy behaviours. See the NEWS file for details.

traceEnabled

A logical value indicating whether actions are logged to a trace file.

cells

A TableCells object containing all of the cells in the body of the table.

allCells

A list of all of the cells in the table, where each element in the list is a 'TableCell' object.

mergedCells

A TableCellRanges object describing the merged cells.

rowCount

The number of rows in the table.

columnCount

The number of columns in the table.

asCharacter

The plain-text representation of the table.

theme

The name of the theme used to style the table. If setting this property, either a theme name can be used, or a list can be used (which specifies a simple theme) or a TableStyles object can be used. See the "Styling" vignette for details and examples.

styles

A TableStyles object containing the styles used to theme the table.

allowExternalStyles

Default FALSE, which means the TableStyles object checks that style names specified for styling the different parts of the table must exist in the styles collection. If they do not an error will occur. Specify TRUE to disable this check, e.g. if the style definitions are not managed by basictabler but instead in an external system.

allTimings

The time taken for various activities related to constructing the table.

significantTimings

The time taken for various activities related to constructing the table, where the elapsed time > 0.1 seconds.

## Methods

### Method new()

Create a new BasicTable object.

#### Details

R6 classes cannot be easily compared to check if two variables are both referring to the same object instance. Instance ids are a mechanism to work around this problem. Each cell is assigned an instance id during object creation, which enables reliable reference comparisons.

#### Returns

An integer instance id.

### Method addData()

Populate the table from a data frame, specifying headers and value formatting.

BasicTable$addData( dataFrame = NULL, columnNamesAsColumnHeaders = TRUE, explicitColumnHeaders = NULL, rowNamesAsRowHeaders = FALSE, firstColumnAsRowHeaders = FALSE, explicitRowHeaders = NULL, numberOfColumnsAsRowHeaders = 0, columnFormats = NULL, fmtFuncArgs = NULL, columnCellTypes = NULL, baseStyleNames = NULL ) #### Arguments dataFrame The data frame to generate the table from. columnNamesAsColumnHeaders TRUE to use the data frame column names as column headings in the table. Default value TRUE. explicitColumnHeaders A character vector of column names to use as column headings in the table. rowNamesAsRowHeaders TRUE to use the data frame row names as row headings in the table. Default value FALSE. firstColumnAsRowHeaders TRUE to use the first column in the data frame as row headings in the table. Default value FALSE. explicitRowHeaders A character vector of row names to use as row headings in the table. numberOfColumnsAsRowHeaders The number of columns to be set as row headers. columnFormats A list that is the same length as the number of columns in the data frame, where each list element specifies how to format the values. Each list element can be either a character format string to be used with sprintf(), a list of arguments to be used with base::format() or a custom R function which will be invoked once per value to be formatted. fmtFuncArgs A list that is the same length as the number of columns in the data frame, where each list element specifies a list of arguments to pass to custom R format functions. columnCellTypes A vector that is the same length as the number of columns in the data frame, where each element is one of the following values that specifies the type of cell: root, rowHeader, columnHeader, cell, total. The cellType controls the default styling that is applied to the cell. Typically only rowHeader, cell or total would be used. baseStyleNames A character vector of style names (from the table theme) used to style the column values. #### Returns No return value. ### Method addMatrix() Populate the table from a matrix, specifying headers and value formatting. #### Usage BasicTable$addMatrix(
matrix = NULL,
columnFormats = NULL,
baseStyleNames = NULL,
fmtFuncArgs = NULL
)

#### Arguments

matrix

The matrix to generate the table from.

columnNamesAsColumnHeaders

TRUE to use the matrix column names as column headings in the table. Default value TRUE.

explicitColumnHeaders

A character vector of column names to use as column headings in the table.

rowNamesAsRowHeaders

TRUE to use the matrix row names as row headings in the table. Default value FALSE.

explicitRowHeaders

A character vector of row names to use as row headings in the table.

columnFormats

A list that is the same length as the number of columns in the matrix, where each list element specifies how to format the values. Each list element can be either a character format string to be used with sprintf(), a list of arguments to be used with base::format() or a custom R function which will be invoked once per value to be formatted.

baseStyleNames

A character vector of style names (from the table theme) used to style the column values.

fmtFuncArgs

A list that is the same length as the number of columns in the data frame, where each list element specifies a list of arguments to pass to custom R format functions.

firstColumnAsRowHeaders

TRUE to use the first column in the matrix as row headings in the table. Default value FALSE.

No return value.

### Method mergeCells()

Merge table cells by specifying either:
The top left cell (rFrom, cFrom) and the merged cell size (rSpan, cSpan) or, The top left cell (rFrom, cFrom) and bottom-right cell (rTo, cTo), or The ranges of rows/columns as vectors using rowNumbers and columnNumbers.

#### Arguments

r

The row number of any cell within the merged cell.

c

The column number of any cell within the merged cell.

errorIfNotFound

TRUE to ignore any attempt to unmerge a cell that is not merged. Default value TRUE.

#### Returns

A new TableCell object.

### Method applyCellMerges()

Internal method that sets the isMerged and mergeIndex properties on each cell based on the cell merges that have been specified.

#### Arguments

value

The value to format.

format

Either a character format string to be used with sprintf(), a list of arguments to be used with base::format() or a custom R function which will be invoked once per value to be formatted.

fmtFuncArgs

If format is a custom R function, then fmtFuncArgs specifies any additional arguments (in the form of a list) that will be passed to the custom function.

#### Returns

The formatted value if format is specified, otherwise the value converted to a character value.

### Method addStyle()

Add a new named style to the table.

#### Arguments

baseStyleName

The name of an existing style to base the new style on.

declarations

CSS style declarations in the form of a list, e.g. list("font-weight"="bold", "color"="#0000FF")

#### Details

Inline styles are typically used to override the style of some specific cells in a table. Inline styles have no name. In HTML, they are rendered as 'style' attributes on specific table cells, where as named styles are linked to cells using the 'class' attribute.

#### Returns

The newly created TableStyle object.

### Method setStyling()

Apply styling to a set of cells in the table.

BasicTable$setStyling( rFrom = NULL, cFrom = NULL, rTo = NULL, cTo = NULL, rowNumbers = NULL, columnNumbers = NULL, cells = NULL, cellType = NULL, visible = NULL, baseStyleName = NULL, style = NULL, declarations = NULL, applyBorderToAdjacentCells = FALSE ) #### Arguments rFrom An integer row number that specifies the start row for the styling changes. cFrom An integer column number that specifies the start column for the styling changes. rTo An integer row number that specifies the end row for the styling changes. cTo An integer column number that specifies the end column for the styling changes. rowNumbers An integer vector that specifies the row numbers for the styling changes. columnNumbers An integer vector that specifies the column numbers for the styling changes. cells A list containing TableCell objects. cellType One of the following values that specifies the type of cell: root, rowHeader, columnHeader, cell, total. The cellType controls the default styling that is applied to the cell. visible The cell visibility to apply (TRUE or FALSE). baseStyleName The name of a style to apply. style A TableStyle object to apply. declarations CSS style declarations to apply in the form of a list, e.g. list("font-weight"="bold", "color"="#0000FF") applyBorderToAdjacentCells TRUE to override the border in neighbouring cells, e.g. the left border of the current cell becomes the right border of the cell to the left. #### Details There are five ways to specify the part(s) of a table to apply styling to: (1) By specifying a list of data groups using the groups argument. (2) By specifying a list of cells using the cells argument. (3) By specifying a single cell using the rFrom and cFrom arguments. (4) By specifying a rectangular cell range using the rFrom, cFrom, rTo and cTo arguments. (5) By specifying a vector of rowNumbers and/or columnNumbers. If both rowNumbers and columnNumbers are specified, then the cells at the intersection of the specified row numbers and column numbers are styled. If both rFrom/rTo and rowNumbers are specified, then rFrom/rTo constrain the row numbers specified in rowNumbers. If both cFrom/cTo and columnNumbers are specified, then cFrom/cTo constrain the column numbers specified in columnNumbers. See the "Styling" and "Finding and Formatting" vignettes for more information and many examples. #### Returns No return value. ### Method mapStyling() Apply styling to table cells based on the value of each cell. #### Usage BasicTable$mapStyling(
styleProperty = NULL,
cells = NULL,
valueType = "text",
mapType = "range",
mappings = NULL,
styleLowerValues = FALSE,
styleHigherValues = TRUE
)

#### Arguments

styleProperty

The name of the style property to set on the specified cells, e.g. background-color.

cells

A list containing TableCell objects.

valueType

The type of style value to be set. Must be one of: "text", "character", "number", "numeric", "color" or "colour".
"text" and "character" are equivalent. "number" and "numeric" are equivalent. "color" and "colour" are equivalent.

mapType

The type of mapping to be performed. The following mapping types are supported:
(1) "value" = a 1:1 mapping which maps each specified "from" value to the corresponding "to" value, e.g. 100 -> "green".
(2) "logic" = each from value is logical criteria. See details.
(3) "range" = values between each pair of "from" values are mapped to the corresponding "to" value, e.g. values in the range 80-100 -> "green" (more specifically values greater than or equal to 80 and less than 100).
(4) "continuous" = rescales values between each pair of "from" values into the range of the corresponding pair of "to" values, e.g. if the "from" range is 80-100 and the corresponding "to" range is 0.8-1, then 90 -> 0.9.
"continuous" cannot be used with valueType="text"/"character".

mappings

The mappings to be applied, specified in one of the following three forms:
(1) a list containing pairs of values, e.g. list(0, "red", 0.4, "yellow", 0.8, "green").
(2) a list containing "from" and "to" vectors/lists, e.g. list(from=c(0, 0.4, 0.8), to=c("red", "yellow", "green")).
(3) a custom mapping function that will be invoked once per cell, e.g. function(v, cell) if(isTRUE(v>0.8)) return("green") .
Mappings must be specified in ascending order when valueType="range" or valueType="continuous".
If a custom mapping function is specified, then the valueType and mapType parameters are ignored.

styleLowerValues

A logical value, default FALSE, that specifies whether values less than the lowest specified "from" value should be styled using the style specified for the lowest "from" value. Only applies when valueType="range" or valueType="continuous".

styleHigherValues

A logical value, default TRUE, that specifies whether values greater than the highest specified "from" value should be styled using the style specified for the highest "from" value. Only applies when valueType="range" or valueType="continuous".

#### Details

mapStyling() is typically used to conditionally apply styling to cells based on the value of each individual cell, e.g. cells with values less than a specified number could be coloured red.
mapType="logic" maps values matching specified logical criteria to specific "to" values. The logical criteria can be any of the following forms (the first matching mapping is used):
(1) a specific value, e.g. 12.
(2) a specific value equality condition, e.g. "v==12", where v represents the cell value.
(3) a value range expression using the following abbreviated form: "value1<=v<value2", e.g. "10<=v<15". Only "<" or "<=" can be used in these value range expressions.
(4) a standard R logical expression, e.g. "10<=v && v<15".
Basic R functions that test the value can also be used, e.g. is.na(v).
See the "Styling" and Finding and Formatting" vignettes for more information and many examples.

No return value.

### Method resetCells()

Clear the cells of the table.

BasicTable$resetCells() #### Details The cells are reset automatically when structural changes are made to the table, so this method often doesn't needs to be called explicitly. #### Returns No return value. ### Method getCells() Retrieve cells by a combination of row and/or column numbers. See the "Finding and Formatting" vignette for graphical examples. #### Usage BasicTable$getCells(
specifyCellsAsList = TRUE,
rowNumbers = NULL,
columnNumbers = NULL,
cellCoordinates = NULL,
excludeEmptyCells = FALSE,
matchMode = "simple"
)

#### Arguments

specifyCellsAsList

Specify how cells are retrieved. Default TRUE. More information is provided in the details section.

rowNumbers

A vector of row numbers that specify the rows or cells to retrieve.

columnNumbers

A vector of column numbers that specify the columns or cells to retrieve.

cellCoordinates

A list of two-element vectors that specify the coordinates of cells to retrieve. Ignored when specifyCellsAsList=FALSE.

excludeEmptyCells

Default FALSE. Specify TRUE to exclude empty cells.

matchMode

Either "simple" (default) or "combinations":
"simple" specifies that row and column arguments are considered separately (logical OR), e.g. rowNumbers=1 and columnNumbers=2 will match all cells in row 1 and all cells in column 2.
"combinations" specifies that row and column arguments are considered together (logical AND), e.g. rowNumbers=1 and columnNumbers=2 will match only the cell single at location (1, 2).
Arguments rowNumbers and columnNumbers are affected by the match mode. All other arguments are not.

#### Details

When specifyCellsAsList=TRUE (the default):
Get one or more rows by specifying the row numbers as a vector as the rowNumbers argument and leaving the columnNumbers argument set to the default value of NULL, or
Get one or more columns by specifying the column numbers as a vector as the columnNumbers argument and leaving the rowNumbers argument set to the default value of NULL, or
Get one or more individual cells by specifying the cellCoordinates argument as a list of vectors of length 2, where each element in the list is the row and column number of one cell,
e.g. list(c(1, 2), c(3, 4)) specifies two cells, the first located at row 1, column 2 and the second located at row 3, column 4.
When specifyCellsAsList=FALSE:
Get one or more rows by specifying the row numbers as a vector as the rowNumbers argument and leaving the columnNumbers argument set to the default value of NULL, or
Get one or more columns by specifying the column numbers as a vector as the columnNumbers argument and leaving the rowNumbers argument set to the default value of NULL, or
Get one or more cells by specifying the row and column numbers as vectors for the rowNumbers and columnNumbers arguments, or
a mixture of the above, where for entire rows/columns the element in the other vector is set to NA, e.g. to retrieve whole rows, specify the row numbers as the rowNumbers but set the corresponding elements in the columnNumbers vector to NA.

#### Returns

A list of TableCell objects.

### Method findCells()

Find cells matching specified criteria. See the "Finding and Formatting" vignette for graphical examples.

#### Arguments

asCharacter

FALSE (default) outputs to the console, specify TRUE to instead return a character value (does not output to console).

#### Returns

Plain text representation of the table.

### Method asMatrix()

Convert the table to a matrix, with or without headings.

BasicTable$asMatrix( firstRowAsColumnNames = FALSE, firstColumnAsRowNames = FALSE, rawValue = FALSE ) #### Arguments firstRowAsColumnNames TRUE to use the first row of the table as the column names in the matrix. Default value FALSE. firstColumnAsRowNames TRUE to use the first column of the table as the row names in the matrix. Default value FALSE. rawValue FALSE (default) outputs the formatted (character) values. Specify TRUE to output the raw cell values. #### Details See the "Outputs" vignette for a comparison of outputs. #### Returns A matrix. ### Method asDataFrame() Convert the table to a data frame, with or without headings. #### Usage BasicTable$asDataFrame(
firstRowAsColumnNames = FALSE,
firstColumnAsRowNames = FALSE,
rawValue = FALSE,
stringsAsFactors = NULL
)

#### Arguments

firstRowAsColumnNames

TRUE to use the first row of the table as the column names in the data frame Default value FALSE.

firstColumnAsRowNames

TRUE to use the first column of the table as the row names in the data frame. Default value FALSE.

rawValue

FALSE (default) outputs the formatted (character) values. Specify TRUE to output the raw cell values.

stringsAsFactors

Specify TRUE to convert strings to factors, default is default.stringsAsFactors() for R < 4.1.0 and FALSE for R >= 4.1.0.

#### Details

See the "Outputs" vignette for a comparison of outputs.

A matrix.

### Method getCss()

Get the CSS declarations for the table.

#### Arguments

styleNamePrefix

A character variable specifying a prefix for all named CSS styles, to avoid style name collisions where multiple tables exist.

#### Details

See the "Outputs" vignette for more details and examples.

#### Returns

A list containing HTML tags from the htmltools package. Convert this to a character variable using as.character().

### Method saveHtml()

Save a HTML representation of the table to file.

#### Arguments

width

The width of the widget.

height

The height of the widget.

styleNamePrefix

A character variable specifying a prefix for all named CSS styles, to avoid style name collisions where multiple tables exist.

#### Details

See the "Outputs" vignette for more details and examples.

#### Returns

A HTML widget from the htmlwidgets package.

### Method writeToExcelWorksheet()

Write the table into the specified workbook and worksheet at the specified row-column location.

#### Arguments

applyStyles

Default TRUE to write styling information for cells.

mapStylesFromCSS

Default TRUE to automatically convert CSS style declarations to their flextable equivalents.

#### Details

See the Outputs vignette for more details.

#### Returns

A table from the flextable package.

### Method trace()

Capture a call for tracing purposes. This is an internal method.

#### Returns

A list of various object properties..

### Method asJSON()

Return the contents of the table as JSON for debugging.

No return value.

### Method finalize()

Clean-up the table.

#### Arguments

deep

Whether to make a deep clone.

## Examples

# The package vignettes have many more examples of working with the
# BasicTable class.
# Quickly rendering a table as an htmlwidget:
library(basictabler)
qhtbl(data.frame(a=1:2, b=3:4))
# Rendering a larger table as an htmlwidget:
library(basictabler)
library(dplyr)
#>
#> Attaching package: ‘dplyr’#> The following objects are masked from ‘package:stats’:
#>
#>     filter, lag#> The following objects are masked from ‘package:base’:
#>
#>     intersect, setdiff, setequal, uniontocsummary <- bhmsummary %>%
group_by(TOC) %>%
summarise(OnTimeArrivals=sum(OnTimeArrivals),
OnTimeDepartures=sum(OnTimeDepartures),
TotalTrains=sum(TrainCount)) %>%
ungroup() %>%
mutate(OnTimeArrivalPercent=OnTimeArrivals/TotalTrains*100,
OnTimeDeparturePercent=OnTimeDepartures/TotalTrains*100) %>%
arrange(TOC)

tbl <- BasicTable$new() columnHeaders <- c("TOC", "On-Time Arrivals", "On-Time Departures", "Total Trains", "On-Time Arrival %", "On-Time Departure %") columnFormats=list() columnFormats[[2]] <- list(big.mark=",") columnFormats[[3]] <- list(big.mark=",") columnFormats[[4]] <- list(big.mark=",") columnFormats[[5]] <- "%.1f" columnFormats[[6]] <- "%.1f" tbl$addData(tocsummary, columnNamesAsColumnHeaders=FALSE,