Title: | Advanced Tables for Markdown/HTML |
---|---|
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. |
Authors: | Max Gordon [aut, cre], Stephen Gragg [aut], Peter Konings [aut] |
Maintainer: | Max Gordon <[email protected]> |
License: | GPL (>= 3) |
Version: | 2.4.3 |
Built: | 2024-11-17 05:26:45 UTC |
Source: | https://github.com/gforge/htmltable |
This function is a preprocessing step before applying the htmlTable()
function.
You use this to style your tables with HTML cascading style sheet features.
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 )
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 )
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 |
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.
x
with the style added as an attribute that the htmlTable then can use for formatting.
css.cell
argumentThe 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))
Other htmlTableStyle:
hasHtmlTableStyle()
library(magrittr) matrix(1:4, ncol = 2) %>% addHtmlTableStyle(align = "c", css.cell = "background-color: orange;") %>% htmlTable(caption = "A simple style example")
library(magrittr) matrix(1:4, ncol = 2) %>% addHtmlTableStyle(align = "c", css.cell = "background-color: orange;") %>% htmlTable(caption = "A simple style example")
htmlTable()
sFunction for concatenating htmlTable()
s
concatHtmlTables(tables, headers = NULL)
concatHtmlTables(tables, headers = NULL)
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. |
htmlTable()
class object
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)
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)
A wrap around the base::attr()
that retrieves the style
attribute used by htmlTable()
(htmlTable.style
).
getHtmlTableStyle(x)
getHtmlTableStyle(x)
x |
The object intended for |
A list
if the attribute exists, otherwise NULL
library(magrittr) mx <- matrix(1:4, ncol = 2) colnames(mx) <- LETTERS[1:2] mx %>% addHtmlTableStyle(align = "l|r") %>% getHtmlTableStyle()
library(magrittr) mx <- matrix(1:4, ncol = 2) colnames(mx) <- LETTERS[1:2] mx %>% addHtmlTableStyle(align = "l|r") %>% getHtmlTableStyle()
htmlTable()
theme listA wrapper for a getOption("htmlTable.theme")()
call that
returns the standard theme unless one is set.
getHtmlTableTheme()
getHtmlTableTheme()
list
with the styles to be applied to the table
getHtmlTableTheme()
getHtmlTableTheme()
If the attribute htmlTable.style
is set it will check if
the style_name
exists and return a logical
.
hasHtmlTableStyle(x, style_name)
hasHtmlTableStyle(x, style_name)
x |
The object intended for |
style_name |
A string that contains the style name. |
logical
TRUE
if the attribute and style is not NULL
Other htmlTableStyle:
addHtmlTableStyle()
library(magrittr) mx <- matrix(1:4, ncol = 2) colnames(mx) <- LETTERS[1:2] mx %>% addHtmlTableStyle(align = "l|r") %>% hasHtmlTableStyle("align")
library(magrittr) mx <- matrix(1:4, ncol = 2) colnames(mx) <- LETTERS[1:2] mx %>% addHtmlTableStyle(align = "l|r") %>% hasHtmlTableStyle("align")
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.
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, ...)
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, ...)
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 |
Returns a formatted string representing an HTML table of class htmlTable
.
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 ""
.
rgroup
argumentThe 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- 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.
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 of rgroup
s to the number
of rgroup
s that aren't empty, i.e. rgroup[rgroup != ""]
. Or a named vector where
the name must correspond to either an rgroup
or to an rgroup
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 dimension nrow(x) x ncol(x)
or
nrow(x) x 1
where the latter is equivalent to a named vector.
If you have rownames
these will resolve similarly to the names to the
list
/vector
arguments. The same thing applies to colnames
.
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 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)
.
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.
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.
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 to cat()
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 to TRUE
so that
the tags and elements are properly indented.
htmlTableCompat
- string - see parameter description
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.
addHtmlTableStyle()
,
setHtmlTableTheme()
,
tidyHtmlTable()
.
txtMergeLines()
,
Hmisc::latex()
Other table functions:
tblNoLast()
,
tblNoNext()
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
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
This widget renders a table with pagination into an htmlwidget
htmlTableWidget( x, number_of_entries = c(10, 25, 100), width = NULL, height = NULL, elementId = NULL, ... )
htmlTableWidget( x, number_of_entries = c(10, 25, 100), width = NULL, height = NULL, elementId = NULL, ... )
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 |
an htmlwidget showing the paginated table
Output and render functions for using htmlTableWidget within Shiny applications and interactive Rmd documents.
htmlTableWidgetOutput(outputId, width = "100%", height = "400px") renderHtmlTableWidget(expr, env = parent.frame(), quoted = FALSE)
htmlTableWidgetOutput(outputId, width = "100%", height = "400px") renderHtmlTableWidget(expr, env = parent.frame(), quoted = FALSE)
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 |
## Not run: # In the UI: htmlTableWidgetOutput("mywidget") # In the server: renderHtmlTableWidget({ htmlTableWidget(iris) }) ## End(Not run)
## 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
innerJoinByCommonCols(x, y)
innerJoinByCommonCols(x, y)
x |
|
y |
|
data.frame
This function wraps the htmlTable and adds JavaScript code for toggling the amount of text shown in any particular cell.
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, ...)
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, ...)
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 |
An htmlTable with a javascript attribute containing the code that is then printed
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"))
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"))
Almost the same as tibble::tibble()
but it solves the issue
with some of the arguments being columns and some just being vectors.
prBindDataListIntoColumns(dataList)
prBindDataListIntoColumns(dataList)
dataList |
|
data.frame
object
Convert all factors to characters to print them as they expected
prConvertDfFactors(x)
prConvertDfFactors(x)
x |
The matrix/data.frame with the data. For the |
The data frame with factors as characters
This function is a wrapper to base::rle()
that
does exactly this but is a little too picky about input values.
prepGroupCounts(x)
prepGroupCounts(x)
x |
The vector to process |
list(n = rle$lengths, names = rle$values)
prepGroupCounts(c(1:3, 3:1))
prepGroupCounts(c(1:3, 3:1))
Removes the htmlEntities from table input data. Note that this also replaces $ signs in order to remove the MathJax issue.
prEscapeHtml(x)
prEscapeHtml(x)
x |
The matrix/data.frame with the data. For the |
x
without the html entities
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
prExtractElementsAndConvertToTbl(x, elements)
prExtractElementsAndConvertToTbl(x, elements)
x |
|
elements |
|
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:
Max Gordon [email protected]
## 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)
## 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)
htmlTable()
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()
.
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 )
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 )
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 |
An invisible list
with the new theme
The styles available are:
standard
: The traditional standard style used in htmlTable()
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 to bottom
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;
.
## Not run: setHtmlTableTheme("Google", align = "r") ## End(Not run)
## Not run: setHtmlTableTheme("Google", align = "r") ## End(Not run)
The function relies on options("table_counter")
in order to keep track of the last number.
tblNoLast(roman = getOption("table_counter_roman", FALSE))
tblNoLast(roman = getOption("table_counter_roman", FALSE))
roman |
Whether or not to use roman numbers instead
of arabic. Can also be set through |
Other table functions:
htmlTable
,
tblNoNext()
org_opts <- options(table_counter=1) tblNoLast() options(org_opts)
org_opts <- options(table_counter=1) tblNoLast() options(org_opts)
The function relies on options("table_counter")
in order to keep track of the last number.
tblNoNext(roman = getOption("table_counter_roman", FALSE))
tblNoNext(roman = getOption("table_counter_roman", FALSE))
roman |
Whether or not to use roman numbers instead
of arabic. Can also be set through |
Other table functions:
htmlTable
,
tblNoLast()
org_opts <- options(table_counter=1) tblNoNext() options(org_opts)
org_opts <- options(table_counter=1) tblNoNext() options(org_opts)
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.
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, ... )
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, ... )
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 |
Returns the HTML code that, when rendered, displays a formatted table.
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.
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.
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.
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
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).
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.
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)
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)
English uses ',' between every 3 numbers while the SI format recommends a ' ' if x > 10^4. The scientific form 10e+? is furthermore avoided.
txtInt( x, language = getOption("htmlTable.language", default = "en"), html = getOption("htmlTable.html", default = TRUE), ... )
txtInt( x, language = getOption("htmlTable.language", default = "en"), html = getOption("htmlTable.html", default = TRUE), ... )
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 |
string
Other text formatters:
txtMergeLines()
,
txtPval()
,
txtRound()
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))
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))
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
txtMergeLines(..., html = 5)
txtMergeLines(..., html = 5)
... |
The lines that you want to be joined |
html |
If HTML compatible output should be used. If |
string
with asis_output
wrapping if html output is activated
Other text formatters:
txtInt()
,
txtPval()
,
txtRound()
txtMergeLines("hello", "world") txtMergeLines("hello", "world", html=FALSE) txtMergeLines("hello", "world", list("A list", "is OK"))
txtMergeLines("hello", "world") txtMergeLines("hello", "world", html=FALSE) txtMergeLines("hello", "world", list("A list", "is OK"))
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.
txtPval(pvalues, lim.2dec = 10^-2, lim.sig = 10^-4, html = TRUE, ...)
txtPval(pvalues, lim.2dec = 10^-2, lim.sig = 10^-4, html = TRUE, ...)
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. |
vector
Other text formatters:
txtInt()
,
txtMergeLines()
,
txtRound()
txtPval(c(0.10234,0.010234, 0.0010234, 0.000010234))
txtPval(c(0.10234,0.010234, 0.0010234, 0.000010234))
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
.
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)
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)
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. |
matrix/data.frame
data.frame
The txtRound
can use data.frame
for input. This allows us to use
tidyselect
patterns as popularized by dplyr.
Other text formatters:
txtInt()
,
txtMergeLines()
,
txtPval()
# 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)
# 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)
Merges all the values and outputs a string formatted as '1st element', '2nd element', ...
vector2string( x, quotation_mark = "'", collapse = sprintf("%s, %s", quotation_mark, quotation_mark) )
vector2string( x, quotation_mark = "'", collapse = sprintf("%s, %s", quotation_mark, quotation_mark) )
x |
The vector to collapse |
quotation_mark |
The type of quote to use |
collapse |
The string that separates each element |
A string with ', '
separation
vector2string(1:4) vector2string(c("a", "b'b", "c")) vector2string(c("a", "b'b", "c"), quotation_mark = '"')
vector2string(1:4) vector2string(c("a", "b'b", "c")) vector2string(c("a", "b'b", "c"), quotation_mark = '"')