Version: | 2.4.3 |
Title: | Advanced Tables for Markdown/HTML |
Maintainer: | Max Gordon <max@gforge.se> |
Description: | Tables with state-of-the-art layout elements such as row spanners, column spanners, table spanners, zebra striping, and more. While allowing advanced layout, the underlying css-structure is simple in order to maximize compatibility with common word processors. The package also contains a few text formatting functions that help outputting text compatible with HTML/LaTeX. |
License: | GPL (≥ 3) |
URL: | https://gforge.se/packages/ |
BugReports: | https://github.com/gforge/htmlTable/issues |
Biarch: | yes |
Depends: | R (≥ 4.1) |
Imports: | stringr, knitr (≥ 1.6), magrittr (≥ 1.5), methods, checkmate, htmlwidgets, htmltools, rstudioapi (≥ 0.6) |
Suggests: | testthat, XML, xml2, Hmisc, rmarkdown, chron, lubridate, tibble, purrr, tidyselect, glue, rlang, tidyr (≥ 0.7.2), dplyr (≥ 0.7.4) |
Encoding: | UTF-8 |
NeedsCompilation: | no |
VignetteBuilder: | knitr |
RoxygenNote: | 7.2.2 |
Packaged: | 2024-07-20 06:52:16 UTC; max |
Author: | Max Gordon [aut, cre], Stephen Gragg [aut], Peter Konings [aut] |
Repository: | CRAN |
Date/Publication: | 2024-07-21 00:30:08 UTC |
Average age in Sweden
Description
For the vignettes there is a dataset downloaded by using the
get_pxweb_data()
call. The data is from
SCB (Statistics Sweden) and downloaded
using the pxweb package:
Author(s)
Max Gordon max@gforge.se
References
Examples
## Not run:
# The data was generated through downloading via the API
library(pxweb)
# Get the last 15 years of data (the data always lags 1 year)
current_year <- as.integer(format(Sys.Date(), "%Y")) -1
SCB <- get_pxweb_data(
url = "http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/BE0101B/BefolkningMedelAlder",
dims = list(Region = c('00', '01', '03', '25'),
Kon = c('1', '2'),
ContentsCode = c('BE0101G9'),
Tid = (current_year-14):current_year),
clean = TRUE)
# Some cleaning was needed before use
SCB$region <- factor(substring(as.character(SCB$region), 4))
Swe_ltrs <- c("å" = "å",
"Å" = "Å",
"ä" = "ä",
"Ä" = "Ä",
"ö" = "ö",
"Ö" = "Ö")
for (i in 1:length(Swe_ltrs)){
levels(SCB$region) <- gsub(names(Swe_ltrs)[i],
Swe_ltrs[i],
levels(SCB$region))
}
save(SCB, file = "data/SCB.rda")
## End(Not run)
Add/set css and other style options
Description
This function is a preprocessing step before applying the htmlTable()
function.
You use this to style your tables with HTML cascading style sheet features.
Usage
addHtmlTableStyle(
x,
align = NULL,
align.header = NULL,
align.cgroup = NULL,
css.rgroup = NULL,
css.rgroup.sep = NULL,
css.tspanner = NULL,
css.tspanner.sep = NULL,
css.total = NULL,
css.cell = NULL,
css.cgroup = NULL,
css.header = NULL,
css.header.border_bottom = NULL,
css.class = NULL,
css.table = NULL,
pos.rowlabel = NULL,
pos.caption = NULL,
col.rgroup = NULL,
col.columns = NULL,
padding.rgroup = NULL,
padding.tspanner = NULL,
spacer.celltype = NULL,
spacer.css.cgroup.bottom.border = NULL,
spacer.css = NULL,
spacer.content = NULL
)
appendHtmlTableStyle(
x,
align = NULL,
align.header = NULL,
align.cgroup = NULL,
css.rgroup = NULL,
css.rgroup.sep = NULL,
css.tspanner = NULL,
css.tspanner.sep = NULL,
css.total = NULL,
css.cell = NULL,
css.cgroup = NULL,
css.header = NULL,
css.header.border_bottom = NULL,
css.class = NULL,
css.table = NULL,
pos.rowlabel = NULL,
pos.caption = NULL,
col.rgroup = NULL,
col.columns = NULL,
padding.rgroup = NULL,
padding.tspanner = NULL,
spacer.celltype = NULL,
spacer.css.cgroup.bottom.border = NULL,
spacer.css = NULL,
spacer.content = NULL
)
Arguments
x |
The object that you later want to pass into |
align |
A character strings specifying column alignments, defaulting to |
align.header |
A character strings specifying alignment for column header,
defaulting to centered, i.e. |
align.cgroup |
The justification of the |
css.rgroup |
CSS style for the rgroup, if different styles are wanted for each of the rgroups you can just specify a vector with the number of elements. |
css.rgroup.sep |
The line between different rgroups. The line is set to the TR element of the lower rgroup, i.e. you have to set the border-top/padding-top etc to a line with the expected function. This is only used for rgroups that are printed. You can specify different separators if you give a vector of rgroup - 1 length (this is since the first rgroup doesn't have a separator). |
css.tspanner |
The CSS style for the table spanner. |
css.tspanner.sep |
The line between different spanners. |
css.total |
The css of the total row if such is activated. |
css.cell |
The css.cell element allows you to add any possible CSS style to your table cells. See section below for details. |
css.cgroup |
The same as |
css.header |
The header style, not including the cgroup style |
css.header.border_bottom |
The header bottom-border style, e.g. |
css.class |
The html CSS class for the table. This allows directing html formatting through CSS directly at all instances of that class. Note: unfortunately the CSS is frequently ignored by word processors. This option is mostly inteded for web-presentations. |
css.table |
You can specify the the style of the table-element using this parameter |
pos.rowlabel |
Where the rowlabel should be positioned. This value can be |
pos.caption |
Set to |
col.rgroup |
Alternating colors (zebra striping/banded rows) for each |
col.columns |
Alternating colors for each column. |
padding.rgroup |
Generally two non-breakings spaces, i.e. |
padding.tspanner |
The table spanner is usually without padding but you may specify padding
similar to |
spacer.celltype |
When using cgroup the table headers are separated through a empty
HTML cell that is by default filled with |
spacer.css.cgroup.bottom.border |
Defaults to |
spacer.css |
If you want the spacer cells to share settings you can set it here |
spacer.content |
Defaults to |
Details
The function stores the current theme (see setHtmlTableTheme()
) + custom styles
to the provided object as an base::attributes()
. It is stored under the element
htmlTable.style
in the form of a list object.
Value
x
with the style added as an attribute that the htmlTable then can use for formatting.
The css.cell
argument
The css.cell
parameter allows you to add any possible CSS style
to your table cells. css.cell
can be either a vector or a matrix.
If css.cell
is a vector, it's assumed that the styles should be repeated
throughout the rows (that is, each element in css.cell specifies the style
for a whole column of 'x').
In the case of css.cell
being a matrix of the same size of the x
argument,
each element of x
gets the style from the corresponding element in css.cell. Additionally,
the number of rows of css.cell
can be nrow(x) + 1
so the first row of of css.cell
specifies the style for the header of x
; also the number of columns of css.cell
can be ncol(x) + 1
to include the specification of style for row names of x
.
Note that the text-align
CSS field in the css.cell
argument will be overriden
by the align
argument.
Excel has a specific css-style, mso-number-format
that can be used for improving the
copy-paste functionality. E.g. the style could be written as: css_matrix <- matrix( data = "mso-number-format:\"\\@\"", nrow = nrow(df), ncol = ncol(df))
See Also
Other htmlTableStyle:
hasHtmlTableStyle()
Examples
library(magrittr)
matrix(1:4, ncol = 2) %>%
addHtmlTableStyle(align = "c", css.cell = "background-color: orange;") %>%
htmlTable(caption = "A simple style example")
Function for concatenating htmlTable()
s
Description
Function for concatenating htmlTable()
s
Usage
concatHtmlTables(tables, headers = NULL)
Arguments
tables |
A list of |
headers |
Either a string or a vector of strings that function as a header for each table. If none is provided it will use the names of the table list or a numeric number. |
Value
htmlTable()
class object
Examples
library(magrittr)
# Basic example
tables <- list()
output <- matrix(1:4,
ncol = 2,
dimnames = list(list("Row 1", "Row 2"),
list("Column 1", "Column 2")))
tables[["Simple table"]] <- htmlTable(output)
# An advanced output
output <- matrix(ncol = 6, nrow = 8)
for (nr in 1:nrow(output)) {
for (nc in 1:ncol(output)) {
output[nr, nc] <-
paste0(nr, ":", nc)
}
}
tables[["Fancy table"]] <- output %>%
addHtmlTableStyle(align = "r",
col.columns = c(rep("none", 2),
rep("#F5FBFF", 4)),
col.rgroup = c("none", "#F7F7F7"),
css.cell = "padding-left: .5em; padding-right: .2em;") %>%
htmlTable(header = paste(c("1st", "2nd",
"3rd", "4th",
"5th", "6th"),
"hdr"),
rnames = paste(c("1st", "2nd",
"3rd",
paste0(4:8, "th")),
"row"),
rgroup = paste("Group", LETTERS[1:3]),
n.rgroup = c(2,4,nrow(output) - 6),
cgroup = rbind(c("", "Column spanners", NA),
c("", "Cgroup 1", "Cgroup 2†")),
n.cgroup = rbind(c(1,2,NA),
c(2,2,2)),
caption = "Basic table with both column spanners (groups) and row groups",
tfoot = "† A table footer commment",
cspan.rgroup = 2)
concatHtmlTables(tables)
Get style options for object
Description
A wrap around the base::attr()
that retrieves the style
attribute used by htmlTable()
(htmlTable.style
).
Usage
getHtmlTableStyle(x)
Arguments
x |
The object intended for |
Value
A list
if the attribute exists, otherwise NULL
Examples
library(magrittr)
mx <- matrix(1:4, ncol = 2)
colnames(mx) <- LETTERS[1:2]
mx %>%
addHtmlTableStyle(align = "l|r") %>%
getHtmlTableStyle()
Retrieve the htmlTable()
theme list
Description
A wrapper for a getOption("htmlTable.theme")()
call that
returns the standard theme unless one is set.
Usage
getHtmlTableTheme()
Value
list
with the styles to be applied to the table
Examples
getHtmlTableTheme()
Check if object has a style set to it
Description
If the attribute htmlTable.style
is set it will check if
the style_name
exists and return a logical
.
Usage
hasHtmlTableStyle(x, style_name)
Arguments
x |
The object intended for |
style_name |
A string that contains the style name. |
Value
logical
TRUE
if the attribute and style is not NULL
See Also
Other htmlTableStyle:
addHtmlTableStyle()
Examples
library(magrittr)
mx <- matrix(1:4, ncol = 2)
colnames(mx) <- LETTERS[1:2]
mx %>%
addHtmlTableStyle(align = "l|r") %>%
hasHtmlTableStyle("align")
Output an HTML table
Description
Generates advanced HTML tables with column and row groups
for a dense representation of complex data. Designed for
maximum compatibility with copy-paste into word processors.
For styling, see addHtmlTableStyle()
and setHtmlTableTheme()
.
Note: If you are using tidyverse and dplyr you may
want to check out tidyHtmlTable()
that automates many of the arguments
that htmlTable
requires.
Usage
htmlTable(
x,
header = NULL,
rnames = NULL,
rowlabel = NULL,
caption = NULL,
tfoot = NULL,
label = NULL,
rgroup = NULL,
n.rgroup = NULL,
cgroup = NULL,
n.cgroup = NULL,
tspanner = NULL,
n.tspanner = NULL,
total = NULL,
ctable = TRUE,
compatibility = getOption("htmlTableCompat", "LibreOffice"),
cspan.rgroup = "all",
escape.html = FALSE,
...
)
## Default S3 method:
htmlTable(
x,
header = NULL,
rnames = NULL,
rowlabel = NULL,
caption = NULL,
tfoot = NULL,
label = NULL,
rgroup = NULL,
n.rgroup = NULL,
cgroup = NULL,
n.cgroup = NULL,
tspanner = NULL,
n.tspanner = NULL,
total = NULL,
ctable = TRUE,
compatibility = getOption("htmlTableCompat", "LibreOffice"),
cspan.rgroup = "all",
escape.html = FALSE,
...
)
## S3 method for class 'htmlTable'
knit_print(x, ...)
## S3 method for class 'htmlTable'
print(x, useViewer, ...)
Arguments
x |
The matrix/data.frame with the data. For the |
header |
A vector of character strings specifying column
header, defaulting to |
rnames |
Default row names are generated from |
rowlabel |
If the table has row names or |
caption |
Adds a table caption. |
tfoot |
Adds a table footer (uses the |
label |
A text string representing a symbolic label for the
table for referencing as an anchor. All you need to do is to reference the
table, for instance |
rgroup |
A vector of character strings containing headings for row groups.
|
n.rgroup |
An integer vector giving the number of rows in each grouping. If |
cgroup |
A vector, matrix or list of character strings defining major column header. The default
is to have none. These elements are also known as column spanners. If you want a column not
to have a spanner then put that column as "". If you pass cgroup and |
n.cgroup |
An integer vector, matrix or list containing the number of columns for which each element in
cgroup is a heading. For example, specify |
tspanner |
The table spanner is somewhat of a table header that you can use when you want to join different tables with the same columns. |
n.tspanner |
An integer vector with the number of rows or |
total |
The last row is sometimes a row total with a border on top and
bold fonts. Set this to |
ctable |
If the table should have a double top border or a single a' la LaTeX ctable style |
compatibility |
Is default set to |
cspan.rgroup |
The number of columns that an |
escape.html |
logical: should HTML characters be escaped? Defaults to FALSE. |
... |
Passed on to |
useViewer |
If you are using RStudio there is a viewer thar can render
the table within that is envoced if in |
Value
Returns a formatted string representing an HTML table of class htmlTable
.
Multiple rows of column spanners cgroup
If you want to have a column spanner in multiple levels (rows) you can
set the cgroup
and n.cgroup
arguments to a matrix
or list
.
For different level elements, set absent ones to NA in a matrix. For example,
cgroup = rbind(c("first", "second", NA), c("a", "b", "c"))
.
And the corresponding n.cgroup
would be n.cgroup = rbind(c(1, 2, NA), c(2, 1, 2))
.
for a table consisting of 5 columns. The "first" spans the first two columns,
the "second" spans the last three columns, "a" spans the first two, "b"
the middle column, and "c" the last two columns.
Using a list is recommended to avoid handling NA
s.
For an empty cgroup
, use ""
.
The rgroup
argument
The rgroup
groups rows seamlessly. Each row in a group is indented by two
spaces (unless the rgroup is ""
) and grouped by its rgroup element. The sum(n.rgroup)
should be zr3ywKOjLZACY4j7TuGXu4v6I8wVWuKy-\leq
matrix rows. If fewer, remaining rows are padded with an empty rgroup (""
). If rgroup
has one more element than n.rgroup
, the last n.rgroup
is computed as nrow(x) - sum(n.rgroup)
for a smoother table generation.
The add attribute to rgroup
To add an extra element at the rgroup
level/row, use attr(rgroup, 'add')
.
The value can either be a vector
, a list
,
or a matrix
. See vignette("general", package = "htmlTable")
for examples.
A
vector
of either equal number ofrgroup
s to the number ofrgroup
s that aren't empty, i.e.rgroup[rgroup != ""]
. Or a named vector where the name must correspond to either anrgroup
or to anrgroup
number.A
list
that has exactly the same requirements as the vector. In addition to the previous we can also have a list with column numbers within as names within the list.A
matrix
with the dimensionnrow(x) x ncol(x)
ornrow(x) x 1
where the latter is equivalent to a named vector. If you haverownames
these will resolve similarly to the names to thelist
/vector
arguments. The same thing applies tocolnames
.
Important knitr-note
This function will only work with knitr outputting HTML, i.e. markdown mode. As the function returns raw HTML-code the compatibility with non-HTML formatting is limited, even with pandoc.
Thanks to the the knitr::knit_print()
and the knitr::asis_output()
the results='asis'
is no longer needed except within for-loops.
If you have a knitr-chunk with a for loop and use print()
to produce
raw HTML you must set the chunk option results='asis'
. Note:
the print-function relies on the base::interactive()
function
for determining if the output should be sent to a browser or to the terminal.
In vignettes and other directly knitted documents you may need to either set
useViewer = FALSE
alternatively set options(htmlTable.cat = TRUE)
.
RStudio's notebook
RStudio has an interactive notebook that allows output directly into the document.
In order for the output to be properly formatted it needs to have the class
of html
. The htmlTable
tries to identify if the environment is a
notebook document (uses the rstudioapi and identifies if its a file with and Rmd
file ending or if there is an element with html_notebook
). If you don't want this
behavior you can remove it using the options(htmlTable.skip_notebook = TRUE)
.
Table counter
If you set the option table_counter you will get a Table 1,2,3
etc before each table, just set options(table_counter=TRUE)
. If
you set it to a number then that number will correspond to the start of
the table_counter. The table_counter
option will also contain the number
of the last table, this can be useful when referencing it in text. By
setting the option options(table_counter_str = "<b>Table %s:</b> ")
you can manipulate the counter table text that is added prior to the
actual caption. Note, you should use the sprintf()
%s
instead of %d
as the software converts all numbers to characters
for compatibility reasons. If you set options(table_counter_roman = TRUE)
then the table counter will use Roman numerals instead of Arabic.
Empty data frames
An empty data frame will result in a warning and output an empty table, provided that
rgroup
and n.rgroup
are not specified. All other row layout options will be ignored.
Options
There are multiple options that can be set, here is a set of the perhaps most used
-
table_counter
- logical - activates a counter for each table -
table_counter_roman
- logical - if true the counter is in Roman numbers, i.e. I, II, III, IV... -
table_counter_str
- string - the string used for generating the table counter text -
useViewer
- logical - if viewer should be used fro printing the table -
htmlTable.cat
- logical - if the output should be directly sent tocat()
-
htmlTable.skip_notebook
- logical - skips the logic for detecting notebook -
htmlTable.pretty_indentation
- logical - there was some issues in previous Pandoc versions where HTML indentation caused everything to be interpreted as code. This seems to be fixed and if you want to look at the raw HTML code it is nice to have this set toTRUE
so that the tags and elements are properly indented. -
htmlTableCompat
- string - see parameter description
Other
Copy-pasting: As you copy-paste results into Word you need to keep the original formatting. Either right click and choose that paste option or click on the icon appearing after a paste. Currently the following compatibilities have been tested with MS Word 2016:
-
Internet Explorer (v. 11.20.10586.0) Works perfectly when copy-pasting into Word
-
RStudio (v. 0.99.448) Works perfectly when copy-pasting into Word. Note: can have issues with multi-line
cgroup
s - see bug -
Chrome (v. 47.0.2526.106) Works perfectly when copy-pasting into Word. Note: can have issues with multi-line
cgroup
s - see bug -
Firefox (v. 43.0.3) Works poorly - looses font-styling, lines and general feel
-
Edge (v. 25.10586.0.0) Works poorly - looses lines and general feel
Direct word processor opening: Opening directly in Libre Office or Word is no longer recommended. You get much prettier results using the cut-and-paste option.
Google docs: Copy-paste directly into a Google docs document is handled rather well. This seems to work especially well when the paste comes directly from a Chrome browser.
Note that when using complex cgroup
alignments with multiple levels
not every browser is able to handle this. For instance the RStudio
webkit browser seems to have issues with this and a
bug has been filed.
As the table uses HTML for rendering you need to be aware of that headers,
row names, and cell values should try respect this for optimal display. Browsers
try to compensate and frequently the tables still turn out fine but it is
not advised. Most importantly you should try to use
<
instead of <
and
>
instead of >
. You can find a complete list
of HTML characters here.
Lastly, I want to mention that function was inspired by the Hmisc::latex()
that can be an excellent alternative if you wish to switch to PDF-output.
For the sibling function tidyHtmlTable()
you can directly switch between
the two using the table_fn
argument.
See Also
addHtmlTableStyle()
,
setHtmlTableTheme()
,
tidyHtmlTable()
.
txtMergeLines()
,
Hmisc::latex()
Other table functions:
tblNoLast()
,
tblNoNext()
Examples
library(magrittr)
# Basic example
output <- matrix(1:4,
ncol = 2,
dimnames = list(list("Row 1", "Row 2"),
list("Column 1", "Column 2")))
htmlTable(output)
invisible(readline(prompt = "Press [enter] to continue"))
# An advanced output
output <- matrix(ncol = 6, nrow = 8)
for (nr in 1:nrow(output)) {
for (nc in 1:ncol(output)) {
output[nr, nc] <-
paste0(nr, ":", nc)
}
}
output %>% addHtmlTableStyle(align = "r",
col.columns = c(rep("none", 2),
rep("#F5FBFF", 4)),
col.rgroup = c("none", "#F7F7F7"),
css.cell = "padding-left: .5em; padding-right: .2em;") %>%
htmlTable(header = paste(c("1st", "2nd",
"3rd", "4th",
"5th", "6th"),
"hdr"),
rnames = paste(c("1st", "2nd",
"3rd",
paste0(4:8, "th")),
"row"),
rgroup = paste("Group", LETTERS[1:3]),
n.rgroup = c(2,4,nrow(output) - 6),
cgroup = rbind(c("", "Column spanners", NA),
c("", "Cgroup 1", "Cgroup 2†")),
n.cgroup = rbind(c(1,2,NA),
c(2,2,2)),
caption = "Basic table with both column spanners (groups) and row groups",
tfoot = "† A table footer commment",
cspan.rgroup = 2)
invisible(readline(prompt = "Press [enter] to continue"))
# An advanced empty table
suppressWarnings({
matrix(ncol = 6,
nrow = 0) %>%
addHtmlTableStyle(col.columns = c(rep("none", 2),
rep("#F5FBFF", 4)),
col.rgroup = c("none", "#F7F7F7"),
css.cell = "padding-left: .5em; padding-right: .2em;") %>%
htmlTable(align = "r",
header = paste(c("1st", "2nd",
"3rd", "4th",
"5th", "6th"),
"hdr"),
cgroup = rbind(c("", "Column spanners", NA),
c("", "Cgroup 1", "Cgroup 2†")),
n.cgroup = rbind(c(1,2,NA),
c(2,2,2)),
caption = "Basic empty table with column spanners (groups) and ignored row colors",
tfoot = "† A table footer commment",
cspan.rgroup = 2)
})
invisible(readline(prompt = "Press [enter] to continue"))
# An example of how to use the css.cell for header styling
simple_output <- matrix(1:4, ncol = 2)
simple_output %>%
addHtmlTableStyle(css.cell = rbind(rep("background: lightgrey; font-size: 2em;",
times = ncol(simple_output)),
matrix("",
ncol = ncol(simple_output),
nrow = nrow(simple_output)))) %>%
htmlTable(header = LETTERS[1:2])
invisible(readline(prompt = "Press [enter] to continue"))
# See vignette("tables", package = "htmlTable")
# for more examples, also check out tidyHtmlTable() that manages
# the group arguments for you through tidy-select syntax
htmlTable with pagination widget
Description
This widget renders a table with pagination into an htmlwidget
Usage
htmlTableWidget(
x,
number_of_entries = c(10, 25, 100),
width = NULL,
height = NULL,
elementId = NULL,
...
)
Arguments
x |
A data frame to be rendered |
number_of_entries |
a numeric vector with the number of entries per page to show. If there is more than one number given, the user will be able to show the number of rows per page in the table. |
width |
Fixed width for widget (in css units). The default is
|
height |
Fixed height for widget (in css units). The default is
|
elementId |
Use an explicit element ID for the widget (rather than an automatically generated one). Useful if you have other JavaScript that needs to explicitly discover and interact with a specific widget instance. |
... |
Additional parameters passed to htmlTable |
Value
an htmlwidget showing the paginated table
Shiny bindings for htmlTableWidget
Description
Output and render functions for using htmlTableWidget within Shiny applications and interactive Rmd documents.
Usage
htmlTableWidgetOutput(outputId, width = "100%", height = "400px")
renderHtmlTableWidget(expr, env = parent.frame(), quoted = FALSE)
Arguments
outputId |
output variable to read from |
width , height |
Must be a valid CSS unit (like |
expr |
An expression that generates a |
env |
The environment in which to evaluate |
quoted |
Is |
Examples
## Not run:
# In the UI:
htmlTableWidgetOutput("mywidget")
# In the server:
renderHtmlTableWidget({
htmlTableWidget(iris)
})
## End(Not run)
A simple function for joining two tables by their intersected columns
Description
A simple function for joining two tables by their intersected columns
Usage
innerJoinByCommonCols(x, y)
Arguments
x |
|
y |
|
Value
data.frame
An interactive table that allows you to limit the size of boxes
Description
This function wraps the htmlTable and adds JavaScript code for toggling the amount of text shown in any particular cell.
Usage
interactiveTable(
x,
...,
txt.maxlen = 20,
button = getOption("htmlTable.interactiveTable.button", default = FALSE),
minimized.columns = NULL,
js.scripts = c()
)
## S3 method for class 'htmlTable'
interactiveTable(
x,
...,
txt.maxlen = 20,
button = getOption("htmlTable.interactiveTable.button", default = FALSE),
minimized.columns = NULL,
js.scripts = c()
)
## S3 method for class 'interactiveTable'
knit_print(x, ...)
## S3 method for class 'interactiveTable'
print(x, useViewer, ...)
Arguments
x |
The table to be printed |
... |
The exact same parameters as |
txt.maxlen |
The maximum length of a text |
button |
Indicator if the cell should be clickable or if a button should appear with a plus/minus |
minimized.columns |
Notifies if any particular columns should be collapsed from start |
js.scripts |
If you want to add your own JavaScript code you can just add it here.
All code is merged into one string where each section is wrapped in it's own
|
useViewer |
If you are using RStudio there is a viewer thar can render
the table within that is envoced if in |
Value
An htmlTable with a javascript attribute containing the code that is then printed
Examples
library(magrittr)
# A simple output
long_txt <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum"
short_txt <- gsub("(^[^.]+).*", "\\1", long_txt)
cbind(rep(short_txt, 2),
rep(long_txt, 2)) %>%
addHtmlTableStyle(col.rgroup = c("#FFF", "#EEF")) %>%
interactiveTable(minimized.columns = ncol(.),
header = c("Short", "Long"),
rnames = c("First", "Second"))
Deprecated use txtInt()
instead.
Description
Deprecated use txtInt()
instead.
Usage
outputInt(...)
Arguments
... |
Passed to |
Examples
## Not run:
# Deprecated function
outputInt(123456)
## End(Not run)
Add a cell
Description
Adds a row of cells <td>val</td><td>...</td>
to a table string for
htmlTable()
Usage
prAddCells(
rowcells,
cellcode,
style_list,
style,
prepped_cell_css,
cgroup_spacer_cells,
has_rn_col,
offset = 1,
style_list_align_key = "align"
)
Arguments
rowcells |
The cells with the values that are to be added |
cellcode |
Type of cell, can either be |
style_list |
The style_list |
style |
The cell style |
cgroup_spacer_cells |
The number of cells that occur between columns due to the cgroup arguments. |
has_rn_col |
Due to the alignment issue we need to keep track of if there has already been printed a rowname column or not and therefore we have this has_rn_col that is either 0 or 1. |
offset |
For rgroup rows there may be an offset != 1 |
Value
string
Returns the string with the new cell elements
See Also
Other hidden helper functions for htmlTable:
prAddEmptySpacerCell()
,
prAddSemicolon2StrEnd()
,
prEscapeHtml()
,
prGetCgroupHeader()
,
prGetRowlabelPos()
,
prGetStyle()
,
prPrepInputMatrixDimensions()
,
prPrepareAlign()
,
prPrepareCgroup()
,
prTblNo()
Add an empty cell
Description
Depending on the spacer.celltype
set in addHtmlTableStyle()
we
will use different spacer cells.
Usage
prAddEmptySpacerCell(
x,
style_list,
cell_style,
align_style,
cell_tag = c("td", "th"),
colspan = 1
)
Arguments
x |
The matrix/data.frame with the data. For the |
cell_style |
The style of the current cell that should be applied to all cells |
align_style |
The style from |
cell_tag |
What HTML tag to use |
colspan |
The number of rows each tag should span |
Value
string
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddSemicolon2StrEnd()
,
prEscapeHtml()
,
prGetCgroupHeader()
,
prGetRowlabelPos()
,
prGetStyle()
,
prPrepInputMatrixDimensions()
,
prPrepareAlign()
,
prPrepareCgroup()
,
prTblNo()
Add a ; at the end
Description
The CSS expects a semicolon at the end of each argument this function just adds a semicolong if none is given and remove multiple semicolon if such exist
Usage
prAddSemicolon2StrEnd(my_str)
Arguments
my_str |
The string that is to be processed |
Value
string
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddEmptySpacerCell()
,
prEscapeHtml()
,
prGetCgroupHeader()
,
prGetRowlabelPos()
,
prGetStyle()
,
prPrepInputMatrixDimensions()
,
prPrepareAlign()
,
prPrepareCgroup()
,
prTblNo()
Get the add attribute element
Description
Gets the add element attribute if it exists. If non-existant it will return NULL.
Usage
prAttr4RgroupAdd(rgroup, rgroup_iterator, no_cols)
Arguments
rgroup |
A vector of character strings containing headings for row groups.
|
rgroup_iterator |
The rgroup number of interest |
no_cols |
The |
Merge columns into a tibble
Description
Almost the same as tibble::tibble()
but it solves the issue
with some of the arguments being columns and some just being vectors.
Usage
prBindDataListIntoColumns(dataList)
Arguments
dataList |
|
Value
data.frame
object
Convert all factors to characters to print them as they expected
Description
Convert all factors to characters to print them as they expected
Usage
prConvertDfFactors(x)
Arguments
x |
The matrix/data.frame with the data. For the |
Value
The data frame with factors as characters
Remove html entities from table
Description
Removes the htmlEntities from table input data. Note that this also replaces $ signs in order to remove the MathJax issue.
Usage
prEscapeHtml(x)
Arguments
x |
The matrix/data.frame with the data. For the |
Value
x
without the html entities
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddEmptySpacerCell()
,
prAddSemicolon2StrEnd()
,
prGetCgroupHeader()
,
prGetRowlabelPos()
,
prGetStyle()
,
prPrepInputMatrixDimensions()
,
prPrepareAlign()
,
prPrepareCgroup()
,
prTblNo()
Extract the elements and generate a table with unique elements
Description
Extract the elements and generate a table with unique elements
Usage
prExtractElementsAndConvertToTbl(x, elements)
Arguments
x |
|
elements |
|
Gets alignment
Description
Gets alignment
Usage
prGetAlign(
align,
index,
style_list = NULL,
spacerCell = FALSE,
followed_by_spacer_cell = FALSE,
previous_was_spacer_cell = FALSE
)
Arguments
align |
A character strings specifying column alignments, defaulting to |
index |
The index of the align parameter of interest |
Retrieve a header row
Description
This function retrieves a header row, i.e. a row
within the <th>
elements on top of the table. Used by
htmlTable()
.
Usage
prGetCgroupHeader(
x,
cgroup_vec,
n.cgroup_vec,
cgroup_vec.just,
row_no,
top_row_style,
rnames,
rowlabel = NULL,
cgroup_spacer_cells,
style_list,
prepped_cell_css,
css_4_cgroup_vec
)
Arguments
x |
The matrix/data.frame with the data. For the |
cgroup_vec |
The |
n.cgroup_vec |
The same as above but for the counter |
cgroup_vec.just |
The same as above bot for the justification |
row_no |
The row number within the header group. Useful for multi-row
headers when we need to output the |
top_row_style |
The top row has a special style depending on
the |
rnames |
Default row names are generated from |
rowlabel |
If the table has row names or |
cgroup_spacer_cells |
The spacer cells due to the multiple cgroup levels.
With multiple rows in cgroup we need to keep track of how many spacer cells
occur between the columns. This variable contains is of the size |
style_list |
The list with all the styles |
Value
string
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddEmptySpacerCell()
,
prAddSemicolon2StrEnd()
,
prEscapeHtml()
,
prGetRowlabelPos()
,
prGetStyle()
,
prPrepInputMatrixDimensions()
,
prPrepareAlign()
,
prPrepareCgroup()
,
prTblNo()
Gets the number of rgroup
HTML line
Description
Gets the number of rgroup
HTML line
Usage
prGetRgroupLine(
x,
total_columns = NULL,
rgroup = NULL,
rgroup_iterator = NULL,
cspan = NULL,
rnames = NULL,
style = NULL,
cgroup_spacer_cells = NULL,
style_list = NULL,
prepped_row_css = NULL
)
Arguments
x |
The matrix/data.frame with the data. For the |
total_columns |
The total number of columns including the |
rgroup |
A vector of character strings containing headings for row groups.
|
rgroup_iterator |
An integer indicating the |
cspan |
The column span of the current |
rnames |
Default row names are generated from |
style |
The css style corresponding to the |
cgroup_spacer_cells |
The vector indicating the position of the |
prepped_row_css |
The |
Gets the rowlabel position
Description
Gets the rowlabel position
Usage
prGetRowlabelPos(cgroup = NULL, pos.rowlabel, header = NULL)
Arguments
cgroup |
A vector, matrix or list of character strings defining major column header. The default
is to have none. These elements are also known as column spanners. If you want a column not
to have a spanner then put that column as "". If you pass cgroup and |
header |
A vector of character strings specifying column
header, defaulting to |
Value
integer
Returns the position within the header rows
to print the rowlabel
argument
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddEmptySpacerCell()
,
prAddSemicolon2StrEnd()
,
prEscapeHtml()
,
prGetCgroupHeader()
,
prGetStyle()
,
prPrepInputMatrixDimensions()
,
prPrepareAlign()
,
prPrepareCgroup()
,
prTblNo()
Gets a string with all the scripts merged into one script tag
Description
Each element has it's own script tags in otherwise an error will cause all the scripts to fail.
Usage
prGetScriptString(x)
Arguments
x |
An interactiveTable |
Value
string
Gets the CSS style element
Description
A function for checking, merging, and more with a variety of different style formats.
Usage
prGetStyle(...)
Arguments
... |
Styles can be provided as |
Value
string
Returns the codes merged into one string with
correct CSS ; and : structure.
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddEmptySpacerCell()
,
prAddSemicolon2StrEnd()
,
prEscapeHtml()
,
prGetCgroupHeader()
,
prGetRowlabelPos()
,
prPrepInputMatrixDimensions()
,
prPrepareAlign()
,
prPrepareCgroup()
,
prTblNo()
Renders the table head (thead)
Description
Renders the table head (thead)
Usage
prGetThead(
x,
header = NULL,
cgroup = NULL,
n.cgroup = NULL,
caption = NULL,
compatibility,
total_columns,
css.cgroup,
top_row_style,
rnames,
rowlabel = NULL,
cgroup_spacer_cells,
prepped_cell_css,
style_list,
cell_style
)
Arguments
x |
The matrix/data.frame with the data. For the |
header |
A vector of character strings specifying column
header, defaulting to |
cgroup |
A vector, matrix or list of character strings defining major column header. The default
is to have none. These elements are also known as column spanners. If you want a column not
to have a spanner then put that column as "". If you pass cgroup and |
n.cgroup |
An integer vector, matrix or list containing the number of columns for which each element in
cgroup is a heading. For example, specify |
caption |
Adds a table caption. |
compatibility |
Is default set to |
total_columns |
The total number of columns including the rowlabel and the specer cells |
top_row_style |
The top row has a special style depending on
the |
rnames |
Default row names are generated from |
rowlabel |
If the table has row names or |
cgroup_spacer_cells |
The spacer cells due to the multiple cgroup levels.
With multiple rows in cgroup we need to keep track of how many spacer cells
occur between the columns. This variable contains is of the size |
style_list |
The list with all the styles |
Value
string
Returns the html string for the <thead>...</thead>
element
Detects if the call is made from within an RStudio Rmd file or a file with the html_notebook output set.
Description
Detects if the call is made from within an RStudio Rmd file or a file with the html_notebook output set.
Usage
prIsNotebook()
Merges multiple colors
Description
Uses the colorRampPalette()
for merging colors.
Note: When merging more than 2 colors the order in the color
presentation matters. Each color is merged with its neigbors before
merging with next. If there is an uneven number of colors the middle
color is mixed with both left and right side.
Usage
prMergeClr(clrs)
Arguments
clrs |
The colors |
Value
character
A hexadecimal color
Makes sure the input is correct
Description
Checks and converts dimensions into something the
htmlTable()
is comfortable with.
Usage
prPrepInputMatrixDimensions(x, header = NULL)
Arguments
x |
The matrix/data.frame with the data. For the |
header |
A vector of character strings specifying column
header, defaulting to |
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddEmptySpacerCell()
,
prAddSemicolon2StrEnd()
,
prEscapeHtml()
,
prGetCgroupHeader()
,
prGetRowlabelPos()
,
prGetStyle()
,
prPrepareAlign()
,
prPrepareCgroup()
,
prTblNo()
Prepares the align to match the columns
Description
The alignment may be tricky and this function therefore simplifies this process by extending/shortening the alignment to match the correct number of columns.
Usage
prPrepareAlign(align, x, rnames, default_rn = "l")
Arguments
x |
The matrix/data.frame with the data. For the |
rnames |
Default row names are generated from |
default_rn |
The default rowname alignment. This is an option as the header uses the same function and there may be differences in how the alignments should be implemented. |
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddEmptySpacerCell()
,
prAddSemicolon2StrEnd()
,
prEscapeHtml()
,
prGetCgroupHeader()
,
prGetRowlabelPos()
,
prGetStyle()
,
prPrepInputMatrixDimensions()
,
prPrepareCgroup()
,
prTblNo()
Prepares the cgroup argument
Description
Due to the complicated structure of multilevel cgroups there some preparation for the cgroup options is required.
Usage
prPrepareCgroup(x, cgroup = NULL, n.cgroup = NULL, style_list)
Arguments
x |
The matrix/data.frame with the data. For the |
cgroup |
A vector, matrix or list of character strings defining major column header. The default
is to have none. These elements are also known as column spanners. If you want a column not
to have a spanner then put that column as "". If you pass cgroup and |
n.cgroup |
An integer vector, matrix or list containing the number of columns for which each element in
cgroup is a heading. For example, specify |
Value
list(cgroup, n.cgroup, align.cgroup, cgroup_spacer_cells)
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddEmptySpacerCell()
,
prAddSemicolon2StrEnd()
,
prEscapeHtml()
,
prGetCgroupHeader()
,
prGetRowlabelPos()
,
prGetStyle()
,
prPrepInputMatrixDimensions()
,
prPrepareAlign()
,
prTblNo()
Prepares the alternating colors
Description
Prepares the alternating colors
Usage
prPrepareColors(clr, n = NULL, ng = NULL, gtxt)
Arguments
clr |
The colors |
n |
The number of rows/columns applicable to the color |
ng |
The n.rgroup/n.cgroup argument if applicable |
gtxt |
The rgroup/cgroup texts |
Value
character
A vector containing hexadecimal colors
Prepares the cell style
Description
Prepares the cell style
Usage
prPrepareCss(
x,
css,
rnames,
header = NULL,
name = deparse(substitute(css)),
style_list = NULL
)
Arguments
x |
The matrix/data.frame with the data. For the |
css |
The CSS styles that are to be converted into a matrix. |
rnames |
Default row names are generated from |
header |
A vector of character strings specifying column
header, defaulting to |
name |
The name of the CSS style that is prepared |
Value
matrix
Returns if rownames should be printed for the htmlTable
Description
Returns if rownames should be printed for the htmlTable
Usage
prSkipRownames(rnames)
Arguments
rnames |
Default row names are generated from |
Gets the table counter string
Description
Returns the string used for htmlTable to number the different tables.
Uses options table_counter
, table_counter_str
,
and table_counter_roman
to produce the final string. You
can set each option by simply calling options()
.
Usage
prTblNo(caption = NULL)
Arguments
caption |
The caption if any |
Value
string
Returns a string formatted according to
the table_counter_str and table_counter_roman. The number is
decided by the table_counter variable
See Also
Other hidden helper functions for htmlTable:
prAddCells()
,
prAddEmptySpacerCell()
,
prAddSemicolon2StrEnd()
,
prEscapeHtml()
,
prGetCgroupHeader()
,
prGetRowlabelPos()
,
prGetStyle()
,
prPrepInputMatrixDimensions()
,
prPrepareAlign()
,
prPrepareCgroup()
Retrieves counts for rgroup, cgroup, & tspanner arguments
Description
This function is a wrapper to base::rle()
that
does exactly this but is a little too picky about input values.
Usage
prepGroupCounts(x)
Arguments
x |
The vector to process |
Value
list(n = rle$lengths, names = rle$values)
Examples
prepGroupCounts(c(1:3, 3:1))
Deprecated use txtPval()
instead
Description
Deprecated use txtPval()
instead
Usage
pvalueFormatter(...)
Arguments
... |
Currently only used for generating warnings of deprecated call |
Examples
## Not run:
# Deprecated function
pvalueFormatter(c(0.10234,0.010234, 0.0010234, 0.000010234))
## End(Not run)
Set or update theme for htmlTable()
Description
The theme guides many of the non-data objects visual appearance. The
theme can be over-ridden by settings for each table. Too get a more complete
understanding of the options, see addHtmlTableStyle()
.
Usage
setHtmlTableTheme(
theme = NULL,
align = NULL,
align.header = NULL,
align.cgroup = NULL,
css.rgroup = NULL,
css.rgroup.sep = NULL,
css.tspanner = NULL,
css.tspanner.sep = NULL,
css.total = NULL,
css.cell = NULL,
css.cgroup = NULL,
css.header = NULL,
css.header.border_bottom = NULL,
css.class = NULL,
css.table = NULL,
pos.rowlabel = NULL,
pos.caption = NULL,
col.rgroup = NULL,
col.columns = NULL,
padding.rgroup = NULL,
padding.tspanner = NULL,
spacer.celltype = NULL,
spacer.css.cgroup.bottom.border = NULL,
spacer.css = NULL,
spacer.content = NULL
)
Arguments
theme |
A |
align |
A character strings specifying column alignments, defaulting to |
align.header |
A character strings specifying alignment for column header,
defaulting to centered, i.e. |
align.cgroup |
The justification of the |
css.rgroup |
CSS style for the rgroup, if different styles are wanted for each of the rgroups you can just specify a vector with the number of elements. |
css.rgroup.sep |
The line between different rgroups. The line is set to the TR element of the lower rgroup, i.e. you have to set the border-top/padding-top etc to a line with the expected function. This is only used for rgroups that are printed. You can specify different separators if you give a vector of rgroup - 1 length (this is since the first rgroup doesn't have a separator). |
css.tspanner |
The CSS style for the table spanner. |
css.tspanner.sep |
The line between different spanners. |
css.total |
The css of the total row if such is activated. |
css.cell |
The css.cell element allows you to add any possible CSS style to your table cells. See section below for details. |
css.cgroup |
The same as |
css.header |
The header style, not including the cgroup style |
css.header.border_bottom |
The header bottom-border style, e.g. |
css.class |
The html CSS class for the table. This allows directing html formatting through CSS directly at all instances of that class. Note: unfortunately the CSS is frequently ignored by word processors. This option is mostly inteded for web-presentations. |
css.table |
You can specify the the style of the table-element using this parameter |
pos.rowlabel |
Where the rowlabel should be positioned. This value can be |
pos.caption |
Set to |
col.rgroup |
Alternating colors (zebra striping/banded rows) for each |
col.columns |
Alternating colors for each column. |
padding.rgroup |
Generally two non-breakings spaces, i.e. |
padding.tspanner |
The table spanner is usually without padding but you may specify padding
similar to |
spacer.celltype |
When using cgroup the table headers are separated through a empty
HTML cell that is by default filled with |
spacer.css.cgroup.bottom.border |
Defaults to |
spacer.css |
If you want the spacer cells to share settings you can set it here |
spacer.content |
Defaults to |
Value
An invisible list
with the new theme
Theme options
The styles available are:
-
standard
: The traditional standard style used inhtmlTable()
since the early days -
Google docs
: A style that is optimized for copy-pasting into documents on Google drive. This is geared towards minimal padding and margins so that the table is as dense as possible. -
blank
: Just as the name suggests the style is completly empty in terms of CSS. Positions for rowlabel and caption are set tobottom
as these cannot be blank.
You can also provide your own style. Each style should be a names vector, e.g. c(width = "100px", color = "red")
or just a real css string, width: 100px; color: red;
.
Examples
## Not run:
setHtmlTableTheme("Google", align = "r")
## End(Not run)
See txtMergeLines()
Description
See txtMergeLines()
Usage
splitLines4Table(...)
Arguments
... |
passed onto |
Examples
## Not run:
# Deprecated function
splitLines4Table("hello", "world")
## End(Not run)
Gets the last table number
Description
The function relies on options("table_counter")
in order to keep track of the last number.
Usage
tblNoLast(roman = getOption("table_counter_roman", FALSE))
Arguments
roman |
Whether or not to use roman numbers instead
of arabic. Can also be set through |
See Also
Other table functions:
htmlTable
,
tblNoNext()
Examples
org_opts <- options(table_counter=1)
tblNoLast()
options(org_opts)
Gets the next table number
Description
The function relies on options("table_counter")
in order to keep track of the last number.
Usage
tblNoNext(roman = getOption("table_counter_roman", FALSE))
Arguments
roman |
Whether or not to use roman numbers instead
of arabic. Can also be set through |
See Also
Other table functions:
htmlTable
,
tblNoLast()
Examples
org_opts <- options(table_counter=1)
tblNoNext()
options(org_opts)
Generate an htmlTable using tidy data as input
Description
This function maps columns from the input data, x
, to htmlTable()
parameters.
It's designed to provide a fluent interface for those familiar with the tidyverse
ecosystem.
Usage
tidyHtmlTable(
x,
value,
header,
rnames,
rgroup,
hidden_rgroup,
cgroup,
tspanner,
hidden_tspanner,
skip_removal_warning = getOption("htmlTable.skip_removal_warning", FALSE),
rnames_unique,
table_fn = htmlTable,
...
)
Arguments
x |
Tidy data used to build the |
value |
Column containing values for individual table cells. Defaults to "value" (same as tidyr::pivot_wider). |
header |
Column in |
rnames |
Column in |
rgroup |
Column in |
Strings indicating | |
cgroup |
Columns in |
tspanner |
Column in |
Strings indicating | |
skip_removal_warning |
Boolean to suppress warnings when removing |
rnames_unique |
Designates unique row names when regular names lack uniqueness. |
table_fn |
Function to format the table, defaults to |
... |
Additional arguments passed to |
Value
Returns the HTML code that, when rendered, displays a formatted table.
Column-mapping
Columns from x
are mapped (transformed) to specific parameters of the htmlTable()
The following columns are converted to match the intended input structure:
-
value
-
header
-
rnames
-
rgroup
-
cgroup
-
tspanner
Each combination of the variables in x
should be unique to map correctly to the output table.
Row uniqueness
Usually each row should have a unique combination of the mappers. Sometimes though rows come in a distinct order and the order identifies the row more than the name. E.g. if we are identifying bone fractures using the AO-classification we will have classes ranging in the form of:
A
A1
A1.1
A2
A2.1
A2.2
B
...
we can simplify the names while retaining the key knowledge to:
A
.1
...1
.2
...1
...2
B
...
This will though result in non-unique rows and thus we need to provide the original
names in addition to the rnames
argument. To do this we have rnames_unique
as a parameter,
without this tidyHtmlTable
we risk unintended merging of cells, generating > 1 value per cell.
Note it is recommended that you verify with the full names just to make sure that any unexpected row order change has happened in the underlying pivot functions.
Sorting
Rows can be pre-sorted using dplyr::arrange()
before passing to tidyHtmlTable
.
Column sorting is based on arrange(cgroup, header)
. If you want to sort in non-alphabetic
order you can provide a factor variable and that information will be retained.
Hidden values
htmlTable
Allows for some values within rgroup
,
cgroup
, etc. to be specified as ""
. The following parameters
allow for specific values to be treated as if they were a string of length
zero in the htmlTable
function.
-
hidden_rgroup
-
hidden_tspanner
Simple tibble output
The tibble discourages the use of row names. There is therefore a convenience
option for tidyHtmlTable
where you can use the function just as you
would with htmlTable()
where rnames
is populated with
the rnames
argument provided using tidyselect
syntax (defaults to
the "names" column if present int the input data).
Additional dependencies
In order to run this function you also must have dplyr, tidyr, tidyselect and purrr packages installed. These have been removed due to the additional 20 Mb that these dependencies added (issue #47). Note: if you use tidyverse it will already have all of these and you do not need to worry.
See Also
Examples
library(tibble)
library(dplyr)
library(tidyr)
# Prep and select basic data
data("mtcars")
base_data <- mtcars %>%
rownames_to_column() %>%
mutate(gear = paste(gear, "Gears"),
cyl = paste(cyl, "Cylinders")) %>%
select(rowname, cyl, gear, wt, mpg, qsec)
base_data %>%
pivot_longer(names_to = "per_metric",
cols = c(wt, mpg, qsec)) %>%
group_by(cyl, gear, per_metric) %>%
summarise(value_Mean = round(mean(value), 1),
value_Min = round(min(value), 1),
value_Max = round(max(value), 1),
.groups = "drop") %>%
pivot_wider(names_from = per_metric,
values_from = starts_with("value_")) %>%
# Round the values into a nicer format where we want the weights to have two decimals
txtRound(ends_with("_wt"), digits = 2) %>%
txtRound(starts_with("value") & !ends_with("_wt"), digits = 1) %>%
# Convert into long format
pivot_longer(cols = starts_with("value_"), names_prefix = "value_") %>%
separate(name, into = c("summary_stat", "per_metric")) %>%
# Without sorting the row groups wont appear right
# If the columns end up in the wrong order you may want to change the columns
# into factors
arrange(per_metric) %>%
addHtmlTableStyle(align = "r") %>%
tidyHtmlTable(
header = gear,
cgroup = cyl,
rnames = summary_stat,
rgroup = per_metric,
skip_removal_warning = TRUE)
SI or English formatting of an integer
Description
English uses ',' between every 3 numbers while the SI format recommends a ' ' if x > 10^4. The scientific form 10e+? is furthermore avoided.
Usage
txtInt(
x,
language = getOption("htmlTable.language", default = "en"),
html = getOption("htmlTable.html", default = TRUE),
...
)
Arguments
x |
The integer variable |
language |
The ISO-639-1 two-letter code for the language of interest. Currently only English is distinguished from the ISO format using a ',' as the separator. |
html |
If the format is used in HTML context
then the space should be a non-breaking space, |
... |
Passed to |
Value
string
See Also
Other text formatters:
txtMergeLines()
,
txtPval()
,
txtRound()
Examples
txtInt(123)
# Supplying a matrix
txtInt(matrix(c(1234, 12345, 123456, 1234567), ncol = 2))
# Missing are returned as empty strings, i.e. ""
txtInt(c(NA, 1e7))
A merges lines while preserving the line break for HTML/LaTeX
Description
This function helps you to do a table header with multiple lines
in both HTML and in LaTeX. In HTML this isn't that tricky, you just use
the <br />
command but in LaTeX I often find
myself writing vbox
/hbox
stuff and therefore
I've created this simple helper function
Usage
txtMergeLines(..., html = 5)
Arguments
... |
The lines that you want to be joined |
html |
If HTML compatible output should be used. If |
Value
string
with asis_output
wrapping if html output is activated
See Also
Other text formatters:
txtInt()
,
txtPval()
,
txtRound()
Examples
txtMergeLines("hello", "world")
txtMergeLines("hello", "world", html=FALSE)
txtMergeLines("hello", "world", list("A list", "is OK"))
Formats the p-values
Description
Gets formatted p-values. For instance
you often want 0.1234
to be 0.12
while also
having two values up until a limit,
i.e. 0.01234
should be 0.012
while
0.001234
should be 0.001
. Furthermore you
want to have < 0.001
as it becomes ridiculous
to report anything below that value.
Usage
txtPval(pvalues, lim.2dec = 10^-2, lim.sig = 10^-4, html = TRUE, ...)
Arguments
pvalues |
The p-values |
lim.2dec |
The limit for showing two decimals. E.g.
the p-value may be |
lim.sig |
The significance limit for the less than sign, i.e. the ' |
html |
If the less than sign should be |
... |
Currently only used for generating warnings of deprecated call parameters. |
Value
vector
See Also
Other text formatters:
txtInt()
,
txtMergeLines()
,
txtRound()
Examples
txtPval(c(0.10234,0.010234, 0.0010234, 0.000010234))
A convenient rounding function
Description
Regular round often looses trailing 0:s as these are truncated, this function
converts everything to strings with all 0:s intact so that tables have the
correct representation, e.g. txtRound(1.01, digits = 1)
turns into 1.0
.
Usage
txtRound(x, ...)
## Default S3 method:
txtRound(
x,
digits = 0,
digits.nonzero = NA,
txt.NA = "",
dec = getOption("htmlTable.decimal_marker", default = "."),
scientific = NULL,
txtInt_args = getOption("htmlTable.round_int", default = NULL),
...
)
## S3 method for class 'table'
txtRound(x, ...)
## S3 method for class 'matrix'
txtRound(x, digits = 0, excl.cols = NULL, excl.rows = NULL, ...)
## S3 method for class 'data.frame'
txtRound(x, ..., digits = 0L)
Arguments
x |
The value/vector/data.frame/matrix to be rounded |
... |
Passed to next method |
digits |
The number of digits to round each element to. For |
digits.nonzero |
The number of digits to keep if the result is close to zero. Sometimes we have an entire table with large numbers only to have a few but interesting observation that are really interesting |
txt.NA |
The string to exchange |
dec |
The decimal marker. If the text is in non-English decimal
and string formatted you need to change this to the appropriate decimal
indicator. The option for this is |
scientific |
If the value should be in scientific format. |
txtInt_args |
A list of arguments to pass to |
excl.cols |
Columns to exclude from the rounding procedure when provided a matrix.
This can be either a number or regular expression. Skipped if |
excl.rows |
Rows to exclude from the rounding procedure when provided a matrix. This can be either a number or regular expression. |
Value
matrix/data.frame
Tidy-select with data.frame
The txtRound
can use data.frame
for input. This allows us to use
tidyselect
patterns as popularized by dplyr.
See Also
Other text formatters:
txtInt()
,
txtMergeLines()
,
txtPval()
Examples
# Basic usage
txtRound(1.023, digits = 1)
# > "1.0"
txtRound(pi, digits = 2)
# > "3.14"
txtRound(12344, digits = 1, txtInt_args = TRUE)
# > "12,344.0"
# Using matrix
mx <- matrix(c(1, 1.11, 1.25,
2.50, 2.55, 2.45,
3.2313, 3, pi),
ncol = 3, byrow=TRUE)
txtRound(mx, digits = 1)
#> [,1] [,2] [,3]
#> [1,] "1.0" "1.1" "1.2"
#> [2,] "2.5" "2.5" "2.5"
#> [3,] "3.2" "3.0" "3.1"
# Using a data.frame directly
library(magrittr)
data("mtcars")
# If we want to round all the numerical values
mtcars %>%
txtRound(digits = 1)
# If we want only want to round some columns
mtcars %>%
txtRound(wt, qsec_txt = qsec, digits = 1)
Collapse vector to string
Description
Merges all the values and outputs a string formatted as '1st element', '2nd element', ...
Usage
vector2string(
x,
quotation_mark = "'",
collapse = sprintf("%s, %s", quotation_mark, quotation_mark)
)
Arguments
x |
The vector to collapse |
quotation_mark |
The type of quote to use |
collapse |
The string that separates each element |
Value
A string with ', '
separation
Examples
vector2string(1:4)
vector2string(c("a", "b'b", "c"))
vector2string(c("a", "b'b", "c"), quotation_mark = '"')