File: htmlTable.Rd

package info (click to toggle)
r-cran-htmltable 2.4.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,600 kB
  • sloc: javascript: 6,797; makefile: 2
file content (431 lines) | stat: -rw-r--r-- 20,228 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/htmlTable.R, R/htmlTable_render_knit_print.R,
%   R/htmlTable_render_print.R
\name{htmlTable}
\alias{htmlTable}
\alias{htmlTable.default}
\alias{knit_print.htmlTable}
\alias{print.htmlTable}
\title{Output an HTML table}
\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,
  ...
)

\method{htmlTable}{default}(
  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,
  ...
)

\method{knit_print}{htmlTable}(x, ...)

\method{print}{htmlTable}(x, useViewer, ...)
}
\arguments{
\item{x}{The matrix/data.frame with the data. For the \code{print} and \code{knit_print}
it takes a string of the class \code{htmlTable} as \code{x} argument.}

\item{header}{A vector of character strings specifying column
header, defaulting to \code{\link[base:colnames]{colnames(x)}}}

\item{rnames}{Default row names are generated from \code{\link[base:colnames]{rownames(x)}}. If you
provide \code{FALSE} then it will skip the row names. \emph{Note:} For \code{data.frames}
if you do \code{\link[base:colnames]{rownames(my_dataframe) <- NULL}} it still has
row names. Thus you need to use \code{FALSE} if you want to
supress row names for \code{data.frames}.}

\item{rowlabel}{If the table has row names or \code{rnames},
\code{rowlabel} is a character string containing the
column heading for the \code{rnames}.}

\item{caption}{Adds a table caption.}

\item{tfoot}{Adds a table footer (uses the \verb{<tfoot>} HTML element). The
output is run through \code{\link[=txtMergeLines]{txtMergeLines()}} simplifying the generation
of multiple lines.}

\item{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 \verb{<a href="#anchor_name">see table 2</a>}. This is
known as the element's id attribute, i.e. table id, in HTML linguo, and should
be unique id for an HTML element in contrast to the \code{css.class} element attribute.}

\item{rgroup}{A vector of character strings containing headings for row groups.
\code{n.rgroup} must be present when \code{rgroup} is given. See
detailed description in section below.}

\item{n.rgroup}{An integer vector giving the number of rows in each grouping. If \code{rgroup}
is not specified, \code{n.rgroup} is just used to divide off blocks of rows by horizontal
lines. If \code{rgroup} is given but \code{n.rgroup} is omitted, \code{n.rgroup} will
default so that each row group contains the same number of rows. If you want additional
rgroup column elements to the cells you can sett the "add" attribute to \code{rgroup} through
\code{attr(rgroup, "add")}, see below explaining section.}

\item{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 \emph{column spanners}. If you want a column \emph{not}
to have a spanner then put that column as "". If you pass cgroup and \code{n.crgroup} as
matrices you can have column spanners for several rows. See cgroup section below for details.}

\item{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 \code{cgroup=c("Major_1","Major_2")},
\code{n.cgroup=c(3,3)} if \code{"Major_1"} is to span columns 1-3 and
\code{"Major_2"} is to span columns 4-6.
\code{rowlabel} does not count in the column numbers. You can omit \code{n.cgroup}
if all groups have the same number of columns. If the \code{n.cgroup} is one less than
the number of columns in the matrix/data.frame then it automatically adds those.}

\item{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.}

\item{n.tspanner}{An integer vector with the number of rows or \code{rgroup}s in the original
matrix that the table spanner should span. If you have provided one fewer n.tspanner elements
the last will be imputed from the number of \code{rgroup}s (if you have provided \code{rgroup} and
\code{sum(n.tspanner) < length(rgroup)}) or the number of rows in the table.}

\item{total}{The last row is sometimes a row total with a border on top and
bold fonts. Set this to \code{TRUE} if you are interested in such a row. If you
want a total row at the end of each table spanner you can set this to \code{"tspanner"}.}

\item{ctable}{If the table should have a double top border or a single a' la LaTeX ctable style}

\item{compatibility}{Is default set to \code{LibreOffice} as some
settings need to be in old HTML format as Libre Office can't
handle some commands such as the css caption-alignment. Note: this
option is not yet fully implemented for all details, in the future
I aim to generate a HTML-correct table and one that is aimed
at Libre Office compatibility. Word-compatibility is difficult as
Word ignores most settings and destroys all layout attempts
(at least that is how my 2010 version behaves). You can additinally use the
\code{options(htmlTableCompat = "html")} if you want a change to apply
to the entire document.
MS Excel sometimes misinterprets certain cell data when opening HTML-tables (eg. 1/2 becomes 1. February).
To avoid this please specify the correct Microsoft Office format for each cell in the table using the css.cell-argument.
To make MS Excel interpret everything as text use "mso-number-format:\"\\@\"".}

\item{cspan.rgroup}{The number of columns that an \code{rgroup} should span. It spans
by default all columns but you may want to limit this if you have column colors
that you want to retain.}

\item{escape.html}{logical: should HTML characters be escaped? Defaults to FALSE.}

\item{...}{Passed on to \code{print.htmlTable} function and any argument except the
\code{useViewer} will be passed on to the \code{\link[base:cat]{base::cat()}} functions arguments.
\emph{Note:} as of version 2.0.0 styling options are still allowed but it is recommended
to instead preprocess your object with \code{\link[=addHtmlTableStyle]{addHtmlTableStyle()}}.}

\item{useViewer}{If you are using RStudio there is a viewer thar can render
the table within that is envoced if in \code{\link[base:interactive]{base::interactive()}} mode.
Set this to \code{FALSE} if you want to remove that  functionality. You can
also force the function to call a specific viewer by setting this to a
viewer function, e.g. \code{useViewer = utils::browseURL} if you want to
override the default RStudio viewer. Another option that does the same is to
set the \code{options(viewer=utils::browseURL)} and it will default to that
particular viewer (this is how RStudio decides on a viewer).
\emph{Note:} If you want to force all output to go through the
\code{\link[base:cat]{base::cat()}} the set \verb{[options][base::options](htmlTable.cat = TRUE)}.}
}
\value{
Returns a formatted string representing an HTML table of class \code{htmlTable}.
}
\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 \code{\link[=addHtmlTableStyle]{addHtmlTableStyle()}} and \code{\link[=setHtmlTableTheme]{setHtmlTableTheme()}}.
\emph{Note:} If you are using \pkg{tidyverse} and \pkg{dplyr} you may
want to check out \code{\link[=tidyHtmlTable]{tidyHtmlTable()}} that automates many of the arguments
that \code{htmlTable} requires.
}
\section{Multiple rows of column spanners \code{cgroup}}{


If you want to have a column spanner in multiple levels (rows) you can
set the \code{cgroup} and \code{n.cgroup} arguments to a \code{matrix} or \code{list}.

For different level elements, set absent ones to NA in a matrix. For example,
\code{cgroup = rbind(c("first", "second", NA), c("a", "b", "c"))}.
And the corresponding \code{n.cgroup} would be \code{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 \code{NA}s.

For an empty \code{cgroup}, use \code{""}.
}

\section{The \code{rgroup} argument}{


The \code{rgroup} groups rows seamlessly. Each row in a group is indented by two
spaces (unless the rgroup is \code{""}) and grouped by its rgroup element. The \code{sum(n.rgroup)}
should be zr3ywKOjLZACY4j7TuGXu4v6I8wVWuKy-\eqn{\leq} matrix rows. If fewer, remaining rows are padded with an empty rgroup (\code{""}). If \code{rgroup}
has one more element than \code{n.rgroup}, the last \code{n.rgroup} is computed as \code{nrow(x) - sum(n.rgroup)}
for a smoother table generation.
}

\section{The add attribute to \code{rgroup}}{


To add an extra element at the \code{rgroup} level/row, use \code{attr(rgroup, 'add')}.
The value can either be a \code{vector}, a \code{list},
or a \code{matrix}. See \code{vignette("general", package = "htmlTable")} for examples.
\itemize{
\item A \code{vector} of either equal number of \code{rgroup}s to the number
of \code{rgroup}s that aren't empty, i.e. \code{rgroup[rgroup != ""]}. Or a named vector where
the name must correspond to either an \code{rgroup} or to an \code{rgroup} number.
\item A \code{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.
\item A \code{matrix} with the dimension \verb{nrow(x) x ncol(x)} or
\verb{nrow(x) x 1} where the latter is equivalent to a named vector.
If you have \code{rownames} these will resolve similarly to the names to the
\code{list}/\code{vector} arguments. The same thing applies to \code{colnames}.
}
}

\section{Important \pkg{knitr}-note}{


This function will only work with \pkg{knitr} outputting \emph{HTML}, i.e.
markdown mode. As the function returns raw HTML-code
the compatibility with non-HTML formatting is limited,
even with \href{https://pandoc.org/}{pandoc}.

Thanks to the the \code{\link[knitr:knit_print]{knitr::knit_print()}} and the \code{\link[knitr:asis_output]{knitr::asis_output()}}
the \code{results='asis'} is \emph{no longer needed} except within for-loops.
If you have a knitr-chunk with a for loop and use \code{print()} to produce
raw HTML you must set the chunk option \code{results='asis'}. \emph{Note}:
the print-function relies on the \code{\link[base:interactive]{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
\code{useViewer = FALSE} alternatively set \code{options(htmlTable.cat = TRUE)}.
}

\section{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 \code{class}
of \code{html}. The \code{htmlTable} tries to identify if the environment is a
notebook document (uses the \pkg{rstudioapi} and identifies if its a file with and \code{Rmd}
file ending or if there is an element with \code{html_notebook}). If you don't want this
behavior you can remove it using the \code{options(htmlTable.skip_notebook = TRUE)}.
}

\section{Table counter}{


If you set the option table_counter you will get a Table 1,2,3
etc before each table, just set \code{options(table_counter=TRUE)}. If
you set it to a number then that number will correspond to the start of
the table_counter. The \code{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 \code{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 \code{\link[=sprintf]{sprintf()}} \verb{\%s}
instead of \verb{\%d} as the software converts all numbers to characters
for compatibility reasons. If you set \code{options(table_counter_roman = TRUE)}
then the table counter will use Roman numerals instead of Arabic.
}

\section{Empty data frames}{

An empty data frame will result in a warning and output an empty table, provided that
\code{rgroup} and \code{n.rgroup} are not specified. All other row layout options will be ignored.
}

\section{Options}{


There are multiple options that can be set, here is a set of the perhaps most used
\itemize{
\item \code{table_counter} - logical - activates a counter for each table
\item \code{table_counter_roman} - logical - if true the counter is in Roman numbers, i.e. I, II, III, IV...
\item \code{table_counter_str} - string - the string used for generating the table counter text
\item \code{useViewer} - logical - if viewer should be used fro printing the table
\item \code{htmlTable.cat} - logical - if the output should be directly sent to \code{cat()}
\item \code{htmlTable.skip_notebook} - logical - skips the logic for detecting notebook
\item \code{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 \code{TRUE} so that
the tags and elements are properly indented.
\item \code{htmlTableCompat} - string - see parameter description
}
}

\section{Other}{


\emph{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:
\itemize{
\item \strong{Internet Explorer} (v. 11.20.10586.0) Works perfectly when copy-pasting into Word
\item \strong{RStudio} (v. 0.99.448) Works perfectly when copy-pasting into Word.
\emph{Note:} can have issues with multi-line \code{cgroup}s -
see \href{https://bugs.chromium.org/p/chromium/issues/detail?id=305130}{bug}
\item \strong{Chrome} (v. 47.0.2526.106) Works perfectly when copy-pasting into Word.
\emph{Note:} can have issues with multi-line \code{cgroup}s -
see \href{https://bugs.chromium.org/p/chromium/issues/detail?id=305130}{bug}
\item \strong{Firefox} (v. 43.0.3) Works poorly - looses font-styling, lines and general feel
\item \strong{Edge} (v. 25.10586.0.0) Works poorly - looses lines and general feel
}

\emph{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.

\emph{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.

\emph{Note} that when using complex \code{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
\href{https://bugs.chromium.org/p/chromium/issues/detail?id=305130}{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
\verb{&lt;} instead of \code{<} and
\verb{&gt;} instead of \code{>}. You can find a complete list
of HTML characters \href{https://ascii.cl/htmlcodes.htm}{here}.

Lastly, I want to mention that function was inspired by the \code{\link[Hmisc:latex]{Hmisc::latex()}}
that can be an excellent alternative if you wish to switch to PDF-output.
For the sibling function \code{\link[=tidyHtmlTable]{tidyHtmlTable()}} you can directly switch between
the two using the \code{table_fn} argument.
}

\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&dagger;")),
            n.cgroup = rbind(c(1,2,NA),
                             c(2,2,2)),
            caption = "Basic table with both column spanners (groups) and row groups",
            tfoot = "&dagger; 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&dagger;")),
              n.cgroup = rbind(c(1,2,NA),
                               c(2,2,2)),
              caption = "Basic empty table with column spanners (groups) and ignored row colors",
              tfoot = "&dagger; 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
}
\seealso{
\code{\link[=addHtmlTableStyle]{addHtmlTableStyle()}},
\code{\link[=setHtmlTableTheme]{setHtmlTableTheme()}},
\code{\link[=tidyHtmlTable]{tidyHtmlTable()}}.
\code{\link[=txtMergeLines]{txtMergeLines()}},
\code{\link[Hmisc:latex]{Hmisc::latex()}}

Other table functions: 
\code{\link{tblNoLast}()},
\code{\link{tblNoNext}()}
}
\concept{table functions}