Debian Codegraph @

R/render-table.R

raw
1 #' Table Output
2 #'
3 #' @description
4 #' The `tableOuptut()`/`renderTable()` pair creates a reactive table that is
5 #' suitable for display small matrices and data frames. The columns are
6 #' formatted with [xtable::xtable()].
7 #'
8 #' See [renderDataTable()] for data frames that are too big to fit on a single
9 #' page.
10 #'
11 #' @param expr An expression that returns an R object that can be used with
12 #' [xtable::xtable()].
13 #' @param striped,hover,bordered Logicals: if `TRUE`, apply the
14 #' corresponding Bootstrap table format to the output table.
15 #' @param spacing The spacing between the rows of the table (`xs`
16 #' stands for "extra small", `s` for "small", `m` for "medium"
17 #' and `l` for "large").
18 #' @param width Table width. Must be a valid CSS unit (like "100%", "400px",
19 #' "auto") or a number, which will be coerced to a string and
20 #' have "px" appended.
21 #' @param align A string that specifies the column alignment. If equal to
22 #' `'l'`, `'c'` or `'r'`, then all columns will be,
23 #' respectively, left-, center- or right-aligned. Otherwise, `align`
24 #' must have the same number of characters as the resulting table (if
25 #' `rownames = TRUE`, this will be equal to `ncol()+1`), with
26 #' the *i*-th character specifying the alignment for the
27 #' *i*-th column (besides `'l'`, `'c'` and
28 #' `'r'`, `'?'` is also permitted - `'?'` is a placeholder
29 #' for that particular column, indicating that it should keep its default
30 #' alignment). If `NULL`, then all numeric/integer columns (including
31 #' the row names, if they are numbers) will be right-aligned and
32 #' everything else will be left-aligned (`align = '?'` produces the
33 #' same result).
34 #' @param rownames,colnames Logicals: include rownames? include colnames
35 #' (column headers)?
36 #' @param digits An integer specifying the number of decimal places for
37 #' the numeric columns (this will not apply to columns with an integer
38 #' class). If `digits` is set to a negative value, then the numeric
39 #' columns will be displayed in scientific format with a precision of
40 #' `abs(digits)` digits.
41 #' @param na The string to use in the table cells whose values are missing
42 #' (i.e. they either evaluate to `NA` or `NaN`).
43 #' @param ... Arguments to be passed through to [xtable::xtable()]
44 #' and [xtable::print.xtable()].
45 #' @inheritParams renderUI
46 #' @param outputArgs A list of arguments to be passed through to the
47 #' implicit call to [tableOutput()] when `renderTable` is
48 #' used in an interactive R Markdown document.
49 #' @export
50 #' @examples
51 #' ## Only run this example in interactive R sessions
52 #' if (interactive()) {
53 #' # table example
54 #' shinyApp(
55 #' ui = fluidPage(
56 #' fluidRow(
57 #' column(12,
58 #' tableOutput('table')
59 #' )
60 #' )
61 #' ),
62 #' server = function(input, output) {
63 #' output$table <- renderTable(iris)
64 #' }
65 #' )
66 #' }
67 renderTable <- function(expr, striped = FALSE, hover = FALSE,
68 bordered = FALSE, spacing = c("s", "xs", "m", "l"),
69 width = "auto", align = NULL,
70 rownames = FALSE, colnames = TRUE,
71 digits = NULL, na = "NA", ...,
72 env = parent.frame(), quoted = FALSE,
73 outputArgs=list())
74 {
75 func <- installExprFunction(expr, "func", env, quoted, label = "renderTable")
76
77 if (!is.function(spacing)) spacing <- match.arg(spacing)
78
79 # A small helper function to create a wrapper for an argument that was
80 # passed to renderTable()
81 createWrapper <- function(arg) {
82 if (is.function(arg)) wrapper <- arg
83 else wrapper <- function() arg
84 return(wrapper)
85 }
86
87 # Create wrappers for most arguments so that functions can also be passed
88 # in, rather than only literals (useful for shiny apps)
89 stripedWrapper <- createWrapper(striped)
90 hoverWrapper <- createWrapper(hover)
91 borderedWrapper <- createWrapper(bordered)
92 spacingWrapper <- createWrapper(spacing)
93 widthWrapper <- createWrapper(width)
94 alignWrapper <- createWrapper(align)
95 rownamesWrapper <- createWrapper(rownames)
96 colnamesWrapper <- createWrapper(colnames)
97 digitsWrapper <- createWrapper(digits)
98 naWrapper <- createWrapper(na)
99
100 dots <- list(...) ## used later (but defined here because of scoping)
101
102 createRenderFunction(
103 func,
104 function(data, session, name, ...) {
105 striped <- stripedWrapper()
106 hover <- hoverWrapper()
107 bordered <- borderedWrapper()
108 format <- c(striped = striped, hover = hover, bordered = bordered)
109 spacing <- spacingWrapper()
110 width <- widthWrapper()
111 align <- alignWrapper()
112 rownames <- rownamesWrapper()
113 colnames <- colnamesWrapper()
114 digits <- digitsWrapper()
115 na <- naWrapper()
116
117 spacing_choices <- c("s", "xs", "m", "l")
118 if (!(spacing %in% spacing_choices)) {
119 stop(paste("`spacing` must be one of",
120 paste0("'", spacing_choices, "'", collapse=", ")))
121 }
122
123 # For css styling
124 classNames <- paste0("table shiny-table",
125 paste0(" table-", names(format)[format], collapse = "" ),
126 paste0(" spacing-", spacing))
127
128 data <- as.data.frame(data)
129
130 # Return NULL if no data is provided
131 if (is.null(data) ||
132 (is.data.frame(data) && nrow(data) == 0 && ncol(data) == 0))
133 return(NULL)
134
135 # Separate the ... args to pass to xtable() vs print.xtable()
136 xtable_argnames <- setdiff(names(formals(xtable)), c("x", "..."))
137 xtable_args <- dots[intersect(names(dots), xtable_argnames)]
138 non_xtable_args <- dots[setdiff(names(dots), xtable_argnames)]
139
140 # By default, numbers are right-aligned and everything else is left-aligned.
141 defaultAlignment <- function(col) {
142 if (is.numeric(col)) "r" else "l"
143 }
144
145 # Figure out column alignment
146 ## Case 1: default alignment
147 if (is.null(align) || align == "?") {
148 names <- defaultAlignment(attr(data, "row.names"))
149 cols <- paste(vapply(data, defaultAlignment, character(1)), collapse = "")
150 cols <- paste0(names, cols)
151 } else {
152 ## Case 2: user-specified alignment
153 num_cols <- if (rownames) nchar(align) else nchar(align)+1
154 valid <- !grepl("[^lcr\\?]", align)
155 if (num_cols == ncol(data)+1 && valid) {
156 cols <- if (rownames) align else paste0("r", align)
157 defaults <- grep("\\?", strsplit(cols,"")[[1]])
158 if (length(defaults) != 0) {
159 vals <- vapply(data[,defaults-1], defaultAlignment, character(1))
160 for (i in seq_len(length(defaults))) {
161 substr(cols, defaults[i], defaults[i]) <- vals[i]
162 }
163 }
164 } else if (nchar(align) == 1 && valid) {
165 cols <- paste0(rep(align, ncol(data)+1), collapse="")
166 } else {
167 stop("`align` must contain only the characters `l`, `c`, `r` and/or `?` and",
168 "have length either equal to 1 or to the total number of columns")
169 }
170 }
171
172 # Call xtable with its (updated) args
173 xtable_args <- c(xtable_args, align = cols, digits = digits)
174 xtable_res <- do.call(xtable, c(list(data), xtable_args))
175
176 # Set up print args
177 print_args <- list(
178 x = xtable_res,
179 type = 'html',
180 include.rownames = {
181 if ("include.rownames" %in% names(dots)) dots$include.rownames
182 else rownames
183 },
184 include.colnames = {
185 if ("include.colnames" %in% names(dots)) dots$include.colnames
186 else colnames
187 },
188 NA.string = {
189 if ("NA.string" %in% names(dots)) dots$NA.string
190 else na
191 },
192 html.table.attributes =
193 paste0({
194 if ("html.table.attributes" %in% names(dots)) dots$html.table.attributes
195 else ""
196 }, " ",
197 "class = '", htmlEscape(classNames, TRUE), "' ",
198 "style = 'width:", validateCssUnit(width), ";'"),
199 comment = {
200 if ("comment" %in% names(dots)) dots$comment
201 else FALSE
202 }
203 )
204
205 print_args <- c(print_args, non_xtable_args)
206 print_args <- print_args[unique(names(print_args))]
207
208 # Capture the raw html table returned by print.xtable(), and store it in
209 # a variable for further processing
210 tab <- paste(utils::capture.output(do.call(print, print_args)),collapse = "\n")
211
212 # Add extra class to cells with NA value, to be able to style them separately
213 tab <- gsub(paste(">", na, "<"), paste(" class='NA'>", na, "<"), tab)
214
215 # All further processing concerns the table headers, so we don't need to run
216 # any of this if colnames=FALSE
217 if (colnames) {
218 # Make sure that the final html table has a proper header (not included
219 # in the print.xtable() default)
220 tab <- sub("<tr>", "<thead> <tr>", tab)
221 tab <- sub("</tr>", "</tr> </thead> <tbody>", tab)
222 tab <- sub("</table>$", "</tbody> </table>", tab)
223
224 # Update the `cols` string (which stores the alignment of each column) so
225 # that it only includes the alignment for the table variables (and not
226 # for the row.names)
227 cols <- if (rownames) cols else substr(cols, 2, nchar(cols))
228
229 # Create a vector whose i-th entry corresponds to the i-th table variable
230 # alignment (substituting "l" by "left", "c" by "center" and "r" by "right")
231 cols <- strsplit(cols, "")[[1]]
232 cols[cols == "l"] <- "left"
233 cols[cols == "r"] <- "right"
234 cols[cols == "c"] <- "center"
235
236 # Align each header accordingly (this guarantees that each header and its
237 # corresponding column have the same alignment)
238 for (i in seq_len(length(cols))) {
239 tab <- sub("<th>", paste0("<th style='text-align: ", cols[i], ";'>"), tab)
240 }
241 }
242 return(tab)
243 },
244 tableOutput, outputArgs
245 )
246 }