Learn R Programming

basictabler

The basictabler package enables rich tables to be created and rendered/exported with just a few lines of R.

The basictabler package:

  • Provides an easy way of creating basic tables, especially from data frames and matrices.
  • Provides flexibility so that the structure/content of the table can be easily built/modified.
  • Provides formatting options to simplify rendering/exporting data.
  • Provides styling options so the tables can be themed/branded as needed.

The tables are rendered as htmlwidgets or plain text. The HTML/text can be exported for use outside of R.

The tables can also be exported to Excel, including the styling/formatting. The formatting/styling is specified once and can then be used when rendering to both HTML and Excel - i.e. it is not necessary to specify the formatting/styling separately for each output format.

Using the flextabler package it is also possible to output tables to Word and PowerPoint.

basictabler is a companion package to the pivottabler package. pivottabler is focussed on generating pivot tables and can aggregate data. basictabler does not aggregate data but offers more control of table structure.

For more information see http://www.basictabler.org.uk/.

Installation

You can install:

  • the latest released version from CRAN with
install.packages("basictabler")
  • the latest development version from github with
devtools::install_github("cbailiss/basictabler", build_vignettes = TRUE)

Examples

Trivial Example

Creating a tiny HTML table from a data frame and immediately rendering it as a htmlwidget:

library(basictabler)
qhtbl(data.frame(a=1:2, b=3:4))

Another Example

Creating a table from a data frame, specifying column names and value formats:

# aggregate the sample data to make a small data frame
library(basictabler)
library(dplyr)
tocsummary <- 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)

# To specify formatting, a list is created which contains one element for each column in 
# the data frame, i.e. tocsummary contains six columns so the columnFormats list has six elements.
# The values in the first column in the data frame won't be formatted since NULL has been specified.
# The values in the 2nd, 3rd and 4th columns will be formatted using format(value, big.mark=",")
# The values in the 5th and 6th columns will be formatted using sprintf(value, "%.1f")
columnFormats=list(NULL, list(big.mark=","), list(big.mark=","), list(big.mark=","), "%.1f", "%.1f")

# render the table directly as a html widget
qhtbl(tocsummary, firstColumnAsRowHeaders=TRUE,
            explicitColumnHeaders=c("TOC", "On-Time Arrivals", "On-Time Departures",
                                    "Total Trains", "On-Time Arrival %", "On-Time Departure %"),
            columnFormats=columnFormats)

In the example above, the qhtbl() functions returns a html widget that is rendered immediately in the R-Studio viewer window. An alternative is to use the qtbl() function which returns a BasicTable object that can be further manipulated. The styling example further below demonstrates this.

Changing a Table Example

Tables can also be built row-by-row, column-by-column and cell-by-cell. Once built tables can be modified (adding/removing rows columns and cells, merging cells and changing styling). The following example shows more granular ways of building and changing a table:

# data for the table
saleIds <- c(5334, 5336, 5338)
items <- c("Apple", "Orange", "Banana")
quantities <- c(5, 8, 6)
prices <- c(0.34452354, 0.4732543, 1.3443243)

# construct a table column by column
library(basictabler)
tbl <- BasicTable$new()
tbl$cells$setCell(1, 1, cellType="root", rawValue="Sale ID")
tbl$cells$setCell(1, 2, cellType="columnHeader", rawValue="Item")
tbl$cells$setCell(1, 3, cellType="columnHeader", rawValue="Quantity")
tbl$cells$setCell(1, 4, cellType="columnHeader", rawValue="Price")
tbl$cells$setColumn(1, cellTypes="rowHeader", rawValues=saleIds)
tbl$cells$setColumn(2, cellTypes="cell", rawValues=items)
tbl$cells$setColumn(3, cellTypes="cell", rawValues=quantities)
tbl$cells$setColumn(4, cellTypes="cell", rawValues=prices,
                    formats=list("%.2f"))

# example of changing the table - appending a row
formats <- list(NULL, NULL, NULL, "%.2f")
cellTypes=c("rowHeader", "cell", "cell", "cell")
tbl$cells$setRow(5, cellTypes=cellTypes, formats=formats, 
                 rawValues=list(5343, "Pear", 2, 1.0213424))

# example of changing the table - inserting a row
tbl$cells$insertRow(1)
tbl$cells$setRow(1, cellTypes="columnHeader",
                 rawValues=list("Sale ID", "Sale Details", "", ""))

# example of changing the table - merging some cells
tbl$mergeCells(rFrom=1, cFrom=1, rSpan=2, cSpan=1)
tbl$mergeCells(rFrom=1, cFrom=2, rSpan=1, cSpan=3)

# render the final table
tbl$renderTable()

Styling Example

Styling can be specified when creating tables:

# aggregate the sample data to make a small data frame
library(basictabler)
library(dplyr)
tocsummary <- 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)

# column formats
columnFormats=list(NULL, list(big.mark=","), list(big.mark=","), list(big.mark=","), "%.1f", "%.1f")

# create the table
tbl <- qtbl(tocsummary, firstColumnAsRowHeaders=FALSE,
            explicitColumnHeaders=c("TOC", "On-Time Arrivals", "On-Time Departures",
                                    "Total Trains", "On-Time Arrival %", "On-Time Departure %"),
            columnFormats=columnFormats, 
            tableStyle=list("border-color"="maroon"),
            headingStyle=list("color"="cornsilk", "background-color"="maroon", 
                              "font-style"="italic", "border-color"="maroon"), 
            cellStyle=list("color"="maroon", "background-color"="cornsilk", 
                           "border-color"="maroon"))

# set column alignment of first column
# the arguments are (rFrom, cFrom, rTo, cTo, declarations)
tbl$setStyling(2, 1, 5, 1, declarations=list("text-align"="left"))

# render table
tbl$renderTable()

Excel Output

The same styling/formatting used for the HTML output is also used when outputting to Excel - greatly reducing the amount of script that needs to be written to create Excel output. The only additional formatting that typically needs applying is the Excel cell format strings.

# aggregate the sample data to make a small data frame
library(basictabler)
library(dplyr)
tocsummary <- 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)

columnFormats=list(NULL, list(big.mark=","), list(big.mark=","), list(big.mark=","), "%.1f", "%.1f")

# create the table
tbl <- qtbl(tocsummary, firstColumnAsRowHeaders=TRUE,
            explicitColumnHeaders=c("TOC", "On-Time Arrivals", "On-Time Departures",
                                    "Total Trains", "On-Time Arrival %", "On-Time Departure %"),
            columnFormats=columnFormats)

# set the styling on the count cells
# the arguments are (rFrom, cFrom, rTo, cTo, declarations)
tbl$setStyling(2, 2, 5, 4, declarations=list("xl-value-format"="#,##0"))
# set the styling on the average delay cells
tbl$setStyling(2, 5, 5, 6, declarations=list("xl-value-format"="##0.0"))

# render the table to an Excel workbook
library(openxlsx)
wb <- createWorkbook(creator = Sys.getenv("USERNAME"))
addWorksheet(wb, "Data")
tbl$writeToExcelWorksheet(wb=wb, wsName="Data", 
                          topRowNumber=2, leftMostColumnNumber=2, applyStyles=TRUE)
saveWorkbook(wb, file="C:\\test.xlsx", overwrite = TRUE)

In the screenshot above, Gridlines have been made invisible to make the styling easier to see (by clearing the checkbox on the 'View' ribbon). Columns were also auto-sized - though the widths of columns could also be manually specified from R. See the Excel Export vignette for more details.

More Information

It is possible to create tables from data frames, matrices, row-by-row, column-by-column and/or cell-by-cell.

Tables can be further manipulated once created, including adding/removing cells/rows/columns and merging cells.

Styling and formatting can be specified for individual cells and ranges of cells.

See the package vignettes for more information:

# to see a list of available package vignettes:
vignette(package="basictabler")
# to open a specific vignette
vignette(topic="v01-introduction", package="basictabler")

The vignettes can also be read on CRAN at: https://cran.r-project.org/package=basictabler

Copy Link

Version

Install

install.packages('basictabler')

Monthly Downloads

678

Version

1.0.4

License

GPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

Christopher Bailiss

Last Published

April 21st, 2025

Functions in basictabler (1.0.4)

TableCellRanges

R6 class that manages cell ranges (e.g. for merged cells).
FlexTableStyle

R6 class that specifies styling as used by the `flextable` package.
TableHtmlRenderer

R6 class that renders a table in HTML.
TableOpenXlsxRenderer

R6 class that renders a table into an Excel worksheet.
PxToPt

Convert a number of pixels to points
TableCell

R6 class that represents a cell in a table.
TableCells

R6 class that manages cells in a table.
FlexTableStyles

R6 class that defines a collection of styles as used by the `flextable` package.
FlexTableRenderer

R6 class that converts a table to a flextable from the `flextabler` package.
BasicTable

R6 class that defines a basic table.
TableOpenXlsxStyles

R6 class that defines a collection of Excel styles as used by the `openxlsx` package.
TableStyles

R6 class that defines a collection of styles.
TableStyle

R6 class that specifies styling.
checkArgument

Perform basic checks on a function argument.
bhmsummary

A Summary of Birmingham Trains, Dec 2016-Feb 2017.
cleanCssValue

Cleans up a CSS attribute value.
basictablerSample

Generate a sample basic table.
TableOpenXlsxStyle

R6 class that specifies Excel styling as used by the openxlsx package.
basictabler

Render a table as a HTML widget.
basictablerOutput

Standard function for Shiny scaffolding.
getCompactTblTheme

Get the compact theme for styling a table.
getFtBorderFromCssBorder

Convert CSS border values to those used by the flextable package.
parseCssSizeToPt

Convert a CSS size value into points.
getNextPosition

Find the first value in an array that is larger than the specified value.
containsText

Check whether a text value is present in another text value.
getSimpleColoredTblTheme

Get a simple coloured theme.
parseCssSizeToPx

Convert a CSS size value into pixels
getDefaultTblTheme

Get the default theme for styling a table.
vreConvertSimpleNumericRange

Convert a simple range expression to a standard R logical expression.
trainstations

Train Stations
getFtBorderWidthFromCssBorder

Convert CSS border width to those used by the flextable package.
getFtBorderStyleFromCssBorder

Convert CSS border style values to those used by the flextable package.
getLargePlainTblTheme

Get the large plain theme for styling a table.
vreIsEqual

Test if two numeric values are equal within tolerance.
vreIsMatch

Test whether a value matches a value range expression.
vreIsSimpleNumericRange

Determine if a value range expression is a simple range expression.
vreIsSingleValue

Determine if a value range expression is a single value.
parseColor

Convert a CSS colour into a hex based colour code.
parseXlBorder

Parse an xl-border value.
parseCssBorder

Parse a CSS border value.
qhtbl

Quickly render a basic table in HTML.
isTextValue

Check whether a text value is present.
oneToNULL

Convert a value of 1 to a NULL value.
getXlBorderFromCssBorder

Convert CSS border style values to those used by the openxlsx package.
getTblTheme

Get a built-in theme for styling a table.
vreHexToClr

Convert a colour in hex format (#RRGGBB) into a list.
vreGetSingleValue

Read the value from a single-valued value range expression.
qtbl

Quickly build a basic table.
renderBasictabler

Standard function for Shiny scaffolding.
vreScale2Colours

Scale a number from a range into a colour gradient.
getBlankTblTheme

Get an empty theme for applying no styling to a table.
getXlBorderStyleFromCssBorder

Convert CSS border values to those used by the openxlsx package.
isNumericValue

Check whether a numeric value is present.
parseFtBorder

Parse an ft-border value.
parseCssString

Split a CSS attribute value into a vector/array.
vreScaleNumber

Rescale a number from one range into another range.