blob: 00d56d9ada8ce629779ce787c4241183dd34e6ce [file] [log] [blame]
Hao Zhuf7994dd2017-02-27 16:58:42 -05001#' Add a header row on top of current header
2#'
3#' @description Tables with multiple rows of header rows are extremely useful
4#' to demonstrate grouped data. This function takes the output of a `kable()`
Hao Zhue7c8f702017-10-10 13:22:59 -04005#' function and adds an header row on top of it.
Hao Zhuf7994dd2017-02-27 16:58:42 -05006#'
7#' @param kable_input Output of `knitr::kable()` with `format` specified
8#' @param header A (named) character vector with `colspan` as values. For
9#' example, `c(" " = 1, "title" = 2)` can be used to create a new header row
10#' for a 3-column table with "title" spanning across column 2 and 3. For
11#' convenience, when `colspan` equals to 1, users can drop the ` = 1` part.
12#' As a result, `c(" ", "title" = 2)` is the same as `c(" " = 1, "title" = 2)`.
Hao Zhu32f43f72017-06-20 18:24:54 -040013#' @param bold A T/F value to control whether the text should be bolded.
14#' @param italic A T/F value to control whether the text should to be emphasized.
Hao Zhuac7e70f2017-08-02 00:18:36 -040015#' @param monospace A T/F value to control whether the text of the selected column
16#' need to be monospaced (verbatim)
Hao Zhu76f0eb62018-09-15 12:38:33 -040017#' @param underline A T/F value to control whether the text of the selected row
18#' need to be underlined
19#' @param strikeout A T/F value to control whether the text of the selected row
20#' need to be stricked out.
Hao Zhu3465b502018-04-02 22:41:46 -040021#' @param align A character string for cell alignment. For HTML, possible values could
22#' be `l`, `c`, `r` plus `left`, `center`, `right`, `justify`, `initial` and `inherit`
23#' while for LaTeX, you can only choose from `l`, `c` & `r`.
Hao Zhu76f0eb62018-09-15 12:38:33 -040024#' @param color A character string/vector for text color. Here please pay
25#' attention to the differences in color codes between HTML and LaTeX.
26#' @param background A character string/vector for background color. Here please
27#' pay attention to the differences in color codes between HTML and LaTeX. Also
28#' note that in HTML, background defined in cell_spec won't cover the whole
29#' cell.
30#' @param font_size A numeric input/vector for font size. For HTML, you can also use
31#' options including `xx-small`, `x-small`, `small`, `medium`, `large`,
32#' `x-large`, `xx-large`, `smaller`, `larger`, `initial` and `inherit`.
33#' @param angle 0-360, degree that the text will rotate.
Hao Zhuac7e70f2017-08-02 00:18:36 -040034#' @param escape A T/F value showing whether special characters should be
35#' escaped.
Salzer6bc84f82018-02-11 13:18:01 -050036#' @param line A T/F value to control whether a line will appear underneath the
37#' header
Hao Zhu6d68f7c2018-09-15 12:44:15 -040038#' @param extra_css An HTML only option. CSS defined here will be send to the
39#' td cell.
Hao Zhuf7994dd2017-02-27 16:58:42 -050040#'
Hao Zhu78e61222017-05-24 20:53:35 -040041#' @examples x <- knitr::kable(head(mtcars), "html")
42#' # Add a row of header with 3 columns on the top of the table. The column
43#' # span for the 2nd and 3rd one are 5 & 6.
44#' add_header_above(x, c(" ", "Group 1" = 5, "Group 2" = 6))
45#'
Hao Zhuc1f38412017-02-23 12:13:48 -050046#' @export
Hao Zhuac7e70f2017-08-02 00:18:36 -040047add_header_above <- function(kable_input, header = NULL,
Hao Zhu76f0eb62018-09-15 12:38:33 -040048 bold = FALSE, italic = FALSE, monospace = FALSE,
49 underline = FALSE, strikeout = FALSE,
50 align = "c", color = NULL, background = NULL,
51 font_size = NULL, angle = NULL,
Hao Zhu6d68f7c2018-09-15 12:44:15 -040052 escape = TRUE, line = TRUE, extra_css = NULL) {
Hao Zhuc1f38412017-02-23 12:13:48 -050053 kable_format <- attr(kable_input, "format")
54 if (!kable_format %in% c("html", "latex")) {
Hao Zhu401ebd82018-01-14 17:10:20 -050055 warning("Please specify format in kable. kableExtra can customize either ",
Hao Zhu76f0eb62018-09-15 12:38:33 -040056 "HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ",
57 "for details.")
Hao Zhu401ebd82018-01-14 17:10:20 -050058 return(kable_input)
Hao Zhuc1f38412017-02-23 12:13:48 -050059 }
60 if (kable_format == "html") {
Hao Zhu3465b502018-04-02 22:41:46 -040061 return(htmlTable_add_header_above(kable_input, header, bold, italic,
Hao Zhu76f0eb62018-09-15 12:38:33 -040062 monospace, underline, strikeout,
Hao Zhu6d68f7c2018-09-15 12:44:15 -040063 align, color, background, font_size,
64 angle, escape, line, extra_css))
Hao Zhuc1f38412017-02-23 12:13:48 -050065 }
66 if (kable_format == "latex") {
Hao Zhu3465b502018-04-02 22:41:46 -040067 return(pdfTable_add_header_above(kable_input, header, bold, italic,
Hao Zhu76f0eb62018-09-15 12:38:33 -040068 monospace, underline, strikeout,
69 align, color, background,
70 font_size, angle, escape, line))
Hao Zhuc1f38412017-02-23 12:13:48 -050071 }
72}
73
74# HTML
Hao Zhu3465b502018-04-02 22:41:46 -040075htmlTable_add_header_above <- function(kable_input, header, bold, italic,
Hao Zhu76f0eb62018-09-15 12:38:33 -040076 monospace, underline, strikeout,
Hao Zhu6d68f7c2018-09-15 12:44:15 -040077 align, color, background, font_size,
78 angle, escape, line, extra_css) {
Hao Zhuc1f38412017-02-23 12:13:48 -050079 if (is.null(header)) return(kable_input)
Hao Zhu909ea382017-06-12 15:43:47 -040080 kable_attrs <- attributes(kable_input)
Hao Zhu558c72f2017-07-24 15:12:00 -040081 kable_xml <- read_kable_as_xml(kable_input)
Hao Zhu62cdde52017-05-20 22:16:03 -040082 kable_xml_thead <- xml_tpart(kable_xml, "thead")
Hao Zhuc1f38412017-02-23 12:13:48 -050083
84 header <- standardize_header_input(header)
85
Hao Zhuac7e70f2017-08-02 00:18:36 -040086 if (escape) {
87 header$header <- escape_html(header$header)
88 }
89
Hao Zhuc1f38412017-02-23 12:13:48 -050090 header_rows <- xml_children(kable_xml_thead)
91 bottom_header_row <- header_rows[[length(header_rows)]]
92 kable_ncol <- length(xml_children(bottom_header_row))
93 if (sum(header$colspan) != kable_ncol) {
94 stop("The new header row you provided has a different total number of ",
95 "columns with the original kable output.")
96 }
97
Hao Zhu76f0eb62018-09-15 12:38:33 -040098 new_header_row <- htmlTable_new_header_generator(
99 header, bold, italic, monospace, underline, strikeout, align, line,
Hao Zhu6d68f7c2018-09-15 12:44:15 -0400100 color, background, font_size, angle, extra_css
Hao Zhu76f0eb62018-09-15 12:38:33 -0400101 )
Hao Zhuc1f38412017-02-23 12:13:48 -0500102 xml_add_child(kable_xml_thead, new_header_row, .where = 0)
Hao Zhuf2dfd142017-07-24 14:43:28 -0400103 out <- as_kable_xml(kable_xml)
Hao Zhu23456762018-03-26 12:30:10 -0400104 if (is.null(kable_attrs$header_above)) {
105 kable_attrs$header_above <- 1
106 } else {
107 kable_attrs$header_above <- kable_attrs$header_above + 1
108 }
Hao Zhu909ea382017-06-12 15:43:47 -0400109 attributes(out) <- kable_attrs
Hao Zhuf2100832018-01-11 16:20:29 -0500110 if (!"kableExtra" %in% class(out)) class(out) <- c("kableExtra", class(out))
Hao Zhu6a076462017-03-01 12:59:01 -0500111 return(out)
Hao Zhuc1f38412017-02-23 12:13:48 -0500112}
113
114standardize_header_input <- function(header) {
115 header_names <- names(header)
116
117 if (is.null(header_names)) {
118 return(data.frame(header = header, colspan = 1, row.names = NULL))
119 }
120
121 names(header)[header_names == ""] <- header[header_names == ""]
122 header[header_names == ""] <- 1
123 header_names <- names(header)
124 header <- as.numeric(header)
125 names(header) <- header_names
126 return(data.frame(header = names(header), colspan = header, row.names = NULL))
127}
128
Hao Zhu76f0eb62018-09-15 12:38:33 -0400129htmlTable_new_header_generator <- function(header_df, bold, italic, monospace,
130 underline, strikeout, align, line,
131 color, background, font_size,
Hao Zhu6d68f7c2018-09-15 12:44:15 -0400132 angle, extra_css) {
Hao Zhu3465b502018-04-02 22:41:46 -0400133 if (align %in% c("l", "c", "r")) {
134 align <- switch(align, r = "right", c = "center", l = "left")
135 }
Hao Zhu32f43f72017-06-20 18:24:54 -0400136 row_style <- paste0(
Hao Zhu3465b502018-04-02 22:41:46 -0400137 paste0("text-align: ", align, "; "),
Hao Zhu32f43f72017-06-20 18:24:54 -0400138 ifelse(bold, "font-weight: bold; ", ""),
Hao Zhuac7e70f2017-08-02 00:18:36 -0400139 ifelse(italic, "font-style: italic; ", ""),
Hao Zhu76f0eb62018-09-15 12:38:33 -0400140 ifelse(monospace, "font-family: monospace; ", ""),
141 ifelse(underline, "text-decoration: underline; ", ""),
142 ifelse(strikeout, "text-decoration: line-through; ", "")
Hao Zhu32f43f72017-06-20 18:24:54 -0400143 )
Hao Zhu76f0eb62018-09-15 12:38:33 -0400144 if (!is.null(color)) {
145 row_style <- paste0(row_style, "color: ", html_color(color), ";")
146 }
147 if (!is.null(background)) {
148 row_style <- paste0(
149 row_style,
150 "padding-right: 4px; padding-left: 4px; ",
151 "background-color: ", html_color(background), ";"
152 )
153 }
154 if (!is.null(font_size)) {
155 if (is.numeric(font_size)) font_size <- paste0(font_size, "px")
156 row_style <- paste0(row_style, "font-size: ", font_size, ";")
157 }
Hao Zhu6d68f7c2018-09-15 12:44:15 -0400158 if (!is.null(extra_css)) {
159 row_style <- paste0(row_style, extra_css)
160 }
161
Hao Zhu76f0eb62018-09-15 12:38:33 -0400162 if (!is.null(angle)) {
163 angle <- paste0("-webkit-transform: rotate(", angle,
164 "deg); -moz-transform: rotate(", angle,
165 "deg); -ms-transform: rotate(", angle,
166 "deg); -o-transform: rotate(", angle,
167 "deg); transform: rotate(", angle,
168 "deg); display: inline-block; ")
169 header_df$header <- ifelse(
170 trimws(header_df$header) == "",
171 header_df$header,
172 paste0('<span style="', angle, '">', header_df$header, '</span>')
173 )
174 }
175
176 line <- ifelse(ez_rep(line, nrow(header_df)),
177 "border-bottom: 1px solid #ddd; padding-bottom: 5px; ", "")
178
179 header_items <- ifelse(
180 trimws(header_df$header) == "",
181 paste0('<th style="border-bottom:hidden" colspan="', header_df$colspan,
182 '"></th>'),
183 paste0(
184 '<th style="border-bottom:hidden; ',
185 'padding-bottom:0; padding-left:3px;padding-right:3px;',
186 row_style, '" colspan="',
187 header_df$colspan, '"><div style="', line, '">', header_df$header,
188 '</div></th>')
189 )
Hao Zhuc1f38412017-02-23 12:13:48 -0500190 header_text <- paste(c("<tr>", header_items, "</tr>"), collapse = "")
191 header_xml <- read_xml(header_text, options = c("COMPACT"))
192 return(header_xml)
193}
194
195# Add an extra header row above the current header in a LaTeX table ------
Hao Zhu3465b502018-04-02 22:41:46 -0400196pdfTable_add_header_above <- function(kable_input, header, bold, italic,
Hao Zhu76f0eb62018-09-15 12:38:33 -0400197 monospace, underline, strikeout,
198 align, color, background,
199 font_size, angle, escape, line) {
Hao Zhuc1f38412017-02-23 12:13:48 -0500200 table_info <- magic_mirror(kable_input)
201 header <- standardize_header_input(header)
Hao Zhu248bbef2018-04-02 18:25:14 -0400202
Hao Zhuac7e70f2017-08-02 00:18:36 -0400203 if (escape) {
Hao Zhuf94a26f2018-04-05 17:42:55 -0400204 header$header <- input_escape(header$header, align)
Hao Zhuac7e70f2017-08-02 00:18:36 -0400205 }
Hao Zhu248bbef2018-04-02 18:25:14 -0400206
Hao Zhu3465b502018-04-02 22:41:46 -0400207 align <- match.arg(align, c("c", "l", "r"))
Hao Zhu248bbef2018-04-02 18:25:14 -0400208
Hao Zhuc1f38412017-02-23 12:13:48 -0500209 hline_type <- switch(table_info$booktabs + 1, "\\\\hline", "\\\\toprule")
Hao Zhu3465b502018-04-02 22:41:46 -0400210 new_header_split <- pdfTable_new_header_generator(
Hao Zhu76f0eb62018-09-15 12:38:33 -0400211 header, table_info$booktabs, bold, italic, monospace, underline, strikeout,
212 align, color, background, font_size, angle)
213 if (line) {
Salzer6bc84f82018-02-11 13:18:01 -0500214 new_header <- paste0(new_header_split[1], "\n", new_header_split[2])
215 } else {
216 new_header <- new_header_split[1]
217 }
Hao Zhu3fc0e882018-04-03 16:06:41 -0400218 out <- str_replace(solve_enc(kable_input),
Hao Zhub2b41992017-10-03 12:50:03 -0400219 hline_type,
220 paste0(hline_type, "\n", new_header))
Hao Zhuc1f38412017-02-23 12:13:48 -0500221 out <- structure(out, format = "latex", class = "knitr_kable")
Hao Zhu2ce42b92017-06-15 17:15:33 -0400222 # new_header_row <- latex_contents_escape(new_header_split[1])
223 if (is.null(table_info$new_header_row)) {
224 table_info$new_header_row <- new_header_split[1]
225 table_info$header_df <- list(header)
226 } else {
227 table_info$new_header_row <- c(table_info$new_header_row, new_header_split[1])
228 table_info$header_df[[length(table_info$header_df) + 1]] <- header
229 }
Hao Zhu32f43f72017-06-20 18:24:54 -0400230 attr(out, "kable_meta") <- table_info
Hao Zhuc1f38412017-02-23 12:13:48 -0500231 return(out)
232}
233
Hao Zhu76f0eb62018-09-15 12:38:33 -0400234ez_rep <- function(x, n) {
235 if (is.null(x)) return(NULL)
236 if (length(x) == 1) return(rep(x, n))
237 return(x)
238}
239
Hao Zhu32f43f72017-06-20 18:24:54 -0400240pdfTable_new_header_generator <- function(header_df, booktabs = FALSE,
Hao Zhu76f0eb62018-09-15 12:38:33 -0400241 bold, italic, monospace,
242 underline, strikeout, align,
243 color, background, font_size, angle) {
244 n <- nrow(header_df)
245 bold <- ez_rep(bold, n)
246 italic <- ez_rep(italic, n)
247 monospace <- ez_rep(monospace, n)
248 underline <- ez_rep(underline, n)
249 strikeout <- ez_rep(strikeout, n)
250 align <- ez_rep(align, n)
251 color <- ez_rep(color, n)
252 background <- ez_rep(background, n)
253 font_size <- ez_rep(font_size, n)
254 angle <- ez_rep(angle, n)
255 if (!booktabs) {
256 align <- paste0("|", align, "|")
257 align[1] <- paste0(align[1], "|")
258 align[nrow(header_df)] <- paste0("|", align[nrow(header_df)])
Hao Zhuc1f38412017-02-23 12:13:48 -0500259 }
Hao Zhu76f0eb62018-09-15 12:38:33 -0400260 header <- header_df$header
261 colspan <- header_df$colspan
262
263 header <- ifelse(bold, paste0('\\\\textbf\\{', header, '\\}'), header)
264 header <- ifelse(italic, paste0('\\\\em\\{', header, '\\}'), header)
265 header <- ifelse(monospace, paste0('\\\\ttfamily\\{', header, '\\}'), header)
266 header <- ifelse(underline, paste0('\\\\underline\\{', header, '\\}'), header)
267 header <- ifelse(strikeout, paste0('\\\\sout\\{', header, '\\}'), header)
268 if (!is.null(color)) {
269 color <- latex_color(color)
270 header <- paste0("\\\\textcolor", color, "\\{", header, "\\}")
271 }
272 if (!is.null(background)) {
273 background <- latex_color(background)
274 header <- paste0("\\\\cellcolor", background, "\\{", header, "\\}")
275 }
276 if (!is.null(font_size)) {
277 header <- paste0("\\\\bgroup\\\\fontsize\\{", font_size, "\\}\\{",
278 as.numeric(font_size) + 2,
279 "\\}\\\\selectfont ", header, "\\\\egroup\\{\\}")
280 }
281 if (!is.null(angle)) {
282 header <- paste0("\\\\rotatebox\\{", angle, "\\}\\{", header, "\\}")
283 }
284 header_items <- paste0(
285 '\\\\multicolumn\\{', colspan, '\\}\\{', align, '\\}\\{', header, '\\}'
286 )
287
Hao Zhuc1f38412017-02-23 12:13:48 -0500288 header_text <- paste(paste(header_items, collapse = " & "), "\\\\\\\\")
Hao Zhu2ce42b92017-06-15 17:15:33 -0400289 cline <- cline_gen(header_df, booktabs)
290 return(c(header_text, cline))
291}
292
293cline_gen <- function(header_df, booktabs) {
Hao Zhuc1f38412017-02-23 12:13:48 -0500294 cline_end <- cumsum(header_df$colspan)
295 cline_start <- c(0, cline_end) + 1
296 cline_start <- cline_start[-length(cline_start)]
Hao Zhuc05e1812017-02-25 01:45:35 -0500297 cline_type <- switch(booktabs + 1,
298 "\\\\cline{",
299 "\\\\cmidrule(l{2pt}r{2pt}){")
Hao Zhuc1f38412017-02-23 12:13:48 -0500300 cline <- paste0(cline_type, cline_start, "-", cline_end, "}")
301 cline <- cline[trimws(header_df$header) != ""]
302 cline <- paste(cline, collapse = " ")
Hao Zhu2ce42b92017-06-15 17:15:33 -0400303 return(cline)
Hao Zhuc1f38412017-02-23 12:13:48 -0500304}
Hao Zhu2ce42b92017-06-15 17:15:33 -0400305
306