blob: c996a12edf016aa7272789163ab13aaba25baba4 [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 Zhub548aac2018-09-18 13:29:01 -040038#' @param line_sep A numeric value indicating how much the midlines should be
39#' separated by space. Default is 3.
Hao Zhu6d68f7c2018-09-15 12:44:15 -040040#' @param extra_css An HTML only option. CSS defined here will be send to the
41#' td cell.
Hao Zhuf64f4752018-10-23 10:35:16 -040042#' @param include_empty Whether empty cells in HTML should also be styled.
43#' Default is FALSE.
Hao Zhu8b2126e2019-04-16 17:58:01 -040044#' @param border_left T/F option for border on the left side in latex.
45#' @param border_right T/F option for border on the right side in latex.
Hao Zhuf7994dd2017-02-27 16:58:42 -050046#'
Hao Zhu78e61222017-05-24 20:53:35 -040047#' @examples x <- knitr::kable(head(mtcars), "html")
48#' # Add a row of header with 3 columns on the top of the table. The column
49#' # span for the 2nd and 3rd one are 5 & 6.
50#' add_header_above(x, c(" ", "Group 1" = 5, "Group 2" = 6))
51#'
Hao Zhuc1f38412017-02-23 12:13:48 -050052#' @export
Hao Zhuac7e70f2017-08-02 00:18:36 -040053add_header_above <- function(kable_input, header = NULL,
Hao Zhu76f0eb62018-09-15 12:38:33 -040054 bold = FALSE, italic = FALSE, monospace = FALSE,
55 underline = FALSE, strikeout = FALSE,
56 align = "c", color = NULL, background = NULL,
57 font_size = NULL, angle = NULL,
Hao Zhub548aac2018-09-18 13:29:01 -040058 escape = TRUE, line = TRUE, line_sep = 3,
Hao Zhu8b2126e2019-04-16 17:58:01 -040059 extra_css = NULL, include_empty = FALSE,
60 border_left = FALSE, border_right = FALSE) {
kbrevoortcd16bc52019-09-03 21:25:33 -040061 if (is.null(header)) return(kable_input)
62
Hao Zhuc1f38412017-02-23 12:13:48 -050063 kable_format <- attr(kable_input, "format")
64 if (!kable_format %in% c("html", "latex")) {
Hao Zhu401ebd82018-01-14 17:10:20 -050065 warning("Please specify format in kable. kableExtra can customize either ",
Hao Zhu76f0eb62018-09-15 12:38:33 -040066 "HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ",
67 "for details.")
Hao Zhu401ebd82018-01-14 17:10:20 -050068 return(kable_input)
Hao Zhuc1f38412017-02-23 12:13:48 -050069 }
70 if (kable_format == "html") {
Hao Zhuf64f4752018-10-23 10:35:16 -040071 return(htmlTable_add_header_above(
72 kable_input, header, bold, italic, monospace, underline, strikeout,
73 align, color, background, font_size, angle, escape, line, line_sep,
74 extra_css, include_empty
75 ))
Hao Zhuc1f38412017-02-23 12:13:48 -050076 }
77 if (kable_format == "latex") {
Hao Zhuf64f4752018-10-23 10:35:16 -040078 return(pdfTable_add_header_above(
79 kable_input, header, bold, italic, monospace, underline, strikeout,
Hao Zhu8b2126e2019-04-16 17:58:01 -040080 align, color, background, font_size, angle, escape, line, line_sep,
81 border_left, border_right))
Hao Zhuc1f38412017-02-23 12:13:48 -050082 }
83}
84
85# HTML
Hao Zhu3465b502018-04-02 22:41:46 -040086htmlTable_add_header_above <- function(kable_input, header, bold, italic,
Hao Zhu76f0eb62018-09-15 12:38:33 -040087 monospace, underline, strikeout,
Hao Zhu6d68f7c2018-09-15 12:44:15 -040088 align, color, background, font_size,
Hao Zhub548aac2018-09-18 13:29:01 -040089 angle, escape, line, line_sep,
Hao Zhuf64f4752018-10-23 10:35:16 -040090 extra_css, include_empty) {
Hao Zhu909ea382017-06-12 15:43:47 -040091 kable_attrs <- attributes(kable_input)
Hao Zhu558c72f2017-07-24 15:12:00 -040092 kable_xml <- read_kable_as_xml(kable_input)
Hao Zhu62cdde52017-05-20 22:16:03 -040093 kable_xml_thead <- xml_tpart(kable_xml, "thead")
Hao Zhuc1f38412017-02-23 12:13:48 -050094
95 header <- standardize_header_input(header)
96
Hao Zhuac7e70f2017-08-02 00:18:36 -040097 if (escape) {
98 header$header <- escape_html(header$header)
99 }
100
Hao Zhuc1f38412017-02-23 12:13:48 -0500101 header_rows <- xml_children(kable_xml_thead)
102 bottom_header_row <- header_rows[[length(header_rows)]]
103 kable_ncol <- length(xml_children(bottom_header_row))
104 if (sum(header$colspan) != kable_ncol) {
105 stop("The new header row you provided has a different total number of ",
106 "columns with the original kable output.")
107 }
108
Hao Zhu76f0eb62018-09-15 12:38:33 -0400109 new_header_row <- htmlTable_new_header_generator(
Hao Zhub548aac2018-09-18 13:29:01 -0400110 header, bold, italic, monospace, underline, strikeout, align,
Hao Zhuf64f4752018-10-23 10:35:16 -0400111 color, background, font_size, angle, line, line_sep, extra_css, include_empty
Hao Zhu76f0eb62018-09-15 12:38:33 -0400112 )
Hao Zhuc1f38412017-02-23 12:13:48 -0500113 xml_add_child(kable_xml_thead, new_header_row, .where = 0)
Hao Zhuf2dfd142017-07-24 14:43:28 -0400114 out <- as_kable_xml(kable_xml)
Hao Zhu23456762018-03-26 12:30:10 -0400115 if (is.null(kable_attrs$header_above)) {
116 kable_attrs$header_above <- 1
117 } else {
118 kable_attrs$header_above <- kable_attrs$header_above + 1
119 }
Hao Zhu909ea382017-06-12 15:43:47 -0400120 attributes(out) <- kable_attrs
Hao Zhuf2100832018-01-11 16:20:29 -0500121 if (!"kableExtra" %in% class(out)) class(out) <- c("kableExtra", class(out))
Hao Zhu6a076462017-03-01 12:59:01 -0500122 return(out)
Hao Zhuc1f38412017-02-23 12:13:48 -0500123}
124
125standardize_header_input <- function(header) {
126 header_names <- names(header)
127
128 if (is.null(header_names)) {
129 return(data.frame(header = header, colspan = 1, row.names = NULL))
130 }
131
132 names(header)[header_names == ""] <- header[header_names == ""]
133 header[header_names == ""] <- 1
134 header_names <- names(header)
135 header <- as.numeric(header)
136 names(header) <- header_names
martinschmelzerf43dcf52019-01-08 13:02:52 +0100137 return(data.frame(header = names(header), colspan = header, row.names = NULL, stringsAsFactors = F))
Hao Zhuc1f38412017-02-23 12:13:48 -0500138}
139
Hao Zhu76f0eb62018-09-15 12:38:33 -0400140htmlTable_new_header_generator <- function(header_df, bold, italic, monospace,
Hao Zhub548aac2018-09-18 13:29:01 -0400141 underline, strikeout, align,
Hao Zhu76f0eb62018-09-15 12:38:33 -0400142 color, background, font_size,
Hao Zhuf64f4752018-10-23 10:35:16 -0400143 angle, line, line_sep, extra_css,
144 include_empty) {
Hao Zhu3465b502018-04-02 22:41:46 -0400145 if (align %in% c("l", "c", "r")) {
146 align <- switch(align, r = "right", c = "center", l = "left")
147 }
Hao Zhu32f43f72017-06-20 18:24:54 -0400148 row_style <- paste0(
Hao Zhu3465b502018-04-02 22:41:46 -0400149 paste0("text-align: ", align, "; "),
Hao Zhu32f43f72017-06-20 18:24:54 -0400150 ifelse(bold, "font-weight: bold; ", ""),
Hao Zhuac7e70f2017-08-02 00:18:36 -0400151 ifelse(italic, "font-style: italic; ", ""),
Hao Zhu76f0eb62018-09-15 12:38:33 -0400152 ifelse(monospace, "font-family: monospace; ", ""),
153 ifelse(underline, "text-decoration: underline; ", ""),
154 ifelse(strikeout, "text-decoration: line-through; ", "")
Hao Zhu32f43f72017-06-20 18:24:54 -0400155 )
Hao Zhu76f0eb62018-09-15 12:38:33 -0400156 if (!is.null(color)) {
Hao Zhu72917f92019-03-15 18:41:42 -0400157 row_style <- paste0(row_style, "color: ", html_color(color), " !important;")
Hao Zhu76f0eb62018-09-15 12:38:33 -0400158 }
159 if (!is.null(background)) {
160 row_style <- paste0(
161 row_style,
162 "padding-right: 4px; padding-left: 4px; ",
Hao Zhu72917f92019-03-15 18:41:42 -0400163 "background-color: ", html_color(background), " !important;"
Hao Zhu76f0eb62018-09-15 12:38:33 -0400164 )
165 }
166 if (!is.null(font_size)) {
167 if (is.numeric(font_size)) font_size <- paste0(font_size, "px")
168 row_style <- paste0(row_style, "font-size: ", font_size, ";")
169 }
Hao Zhu6d68f7c2018-09-15 12:44:15 -0400170 if (!is.null(extra_css)) {
171 row_style <- paste0(row_style, extra_css)
172 }
173
Hao Zhu76f0eb62018-09-15 12:38:33 -0400174 if (!is.null(angle)) {
175 angle <- paste0("-webkit-transform: rotate(", angle,
176 "deg); -moz-transform: rotate(", angle,
177 "deg); -ms-transform: rotate(", angle,
178 "deg); -o-transform: rotate(", angle,
179 "deg); transform: rotate(", angle,
180 "deg); display: inline-block; ")
Hao Zhuf64f4752018-10-23 10:35:16 -0400181 if (include_empty) {
182 header_df$header <- paste0('<span style="', angle, '">',
183 header_df$header, '</span>')
184 } else {
185 header_df$header <- ifelse(
186 trimws(header_df$header) == "",
187 header_df$header,
188 paste0('<span style="', angle, '">', header_df$header, '</span>')
189 )
190 }
Hao Zhu76f0eb62018-09-15 12:38:33 -0400191 }
192
193 line <- ifelse(ez_rep(line, nrow(header_df)),
194 "border-bottom: 1px solid #ddd; padding-bottom: 5px; ", "")
Hao Zhub548aac2018-09-18 13:29:01 -0400195 line_sep <- ez_rep(line_sep, nrow(header_df))
196 line_sep <- glue::glue('padding-left:{line_sep}px;padding-right:{line_sep}px;')
Hao Zhu76f0eb62018-09-15 12:38:33 -0400197
198 header_items <- ifelse(
199 trimws(header_df$header) == "",
200 paste0('<th style="border-bottom:hidden" colspan="', header_df$colspan,
201 '"></th>'),
202 paste0(
Hao Zhub548aac2018-09-18 13:29:01 -0400203 '<th style="border-bottom:hidden; padding-bottom:0; ',
204 line_sep, row_style, '" colspan="',
Hao Zhu76f0eb62018-09-15 12:38:33 -0400205 header_df$colspan, '"><div style="', line, '">', header_df$header,
206 '</div></th>')
207 )
Hao Zhuc1f38412017-02-23 12:13:48 -0500208 header_text <- paste(c("<tr>", header_items, "</tr>"), collapse = "")
209 header_xml <- read_xml(header_text, options = c("COMPACT"))
210 return(header_xml)
211}
212
213# Add an extra header row above the current header in a LaTeX table ------
Hao Zhu3465b502018-04-02 22:41:46 -0400214pdfTable_add_header_above <- function(kable_input, header, bold, italic,
Hao Zhub548aac2018-09-18 13:29:01 -0400215 monospace, underline, strikeout, align,
216 color, background, font_size, angle,
Hao Zhu8b2126e2019-04-16 17:58:01 -0400217 escape, line, line_sep,
218 border_left, border_right) {
Hao Zhuc1f38412017-02-23 12:13:48 -0500219 table_info <- magic_mirror(kable_input)
220 header <- standardize_header_input(header)
Hao Zhu248bbef2018-04-02 18:25:14 -0400221
Hao Zhuac7e70f2017-08-02 00:18:36 -0400222 if (escape) {
Hao Zhuf94a26f2018-04-05 17:42:55 -0400223 header$header <- input_escape(header$header, align)
Hao Zhuac7e70f2017-08-02 00:18:36 -0400224 }
Hao Zhu248bbef2018-04-02 18:25:14 -0400225
Hao Zhu3465b502018-04-02 22:41:46 -0400226 align <- match.arg(align, c("c", "l", "r"))
Hao Zhu248bbef2018-04-02 18:25:14 -0400227
Hao Zhuc1f38412017-02-23 12:13:48 -0500228 hline_type <- switch(table_info$booktabs + 1, "\\\\hline", "\\\\toprule")
Hao Zhu3465b502018-04-02 22:41:46 -0400229 new_header_split <- pdfTable_new_header_generator(
Hao Zhu76f0eb62018-09-15 12:38:33 -0400230 header, table_info$booktabs, bold, italic, monospace, underline, strikeout,
Hao Zhu8b2126e2019-04-16 17:58:01 -0400231 align, color, background, font_size, angle, line_sep,
232 border_left, border_right)
Hao Zhu76f0eb62018-09-15 12:38:33 -0400233 if (line) {
Salzer6bc84f82018-02-11 13:18:01 -0500234 new_header <- paste0(new_header_split[1], "\n", new_header_split[2])
235 } else {
236 new_header <- new_header_split[1]
237 }
Hao Zhu3fc0e882018-04-03 16:06:41 -0400238 out <- str_replace(solve_enc(kable_input),
Hao Zhub2b41992017-10-03 12:50:03 -0400239 hline_type,
240 paste0(hline_type, "\n", new_header))
Hao Zhuc1f38412017-02-23 12:13:48 -0500241 out <- structure(out, format = "latex", class = "knitr_kable")
Hao Zhu2ce42b92017-06-15 17:15:33 -0400242 # new_header_row <- latex_contents_escape(new_header_split[1])
243 if (is.null(table_info$new_header_row)) {
244 table_info$new_header_row <- new_header_split[1]
245 table_info$header_df <- list(header)
246 } else {
247 table_info$new_header_row <- c(table_info$new_header_row, new_header_split[1])
248 table_info$header_df[[length(table_info$header_df) + 1]] <- header
249 }
Hao Zhu32f43f72017-06-20 18:24:54 -0400250 attr(out, "kable_meta") <- table_info
Hao Zhuc1f38412017-02-23 12:13:48 -0500251 return(out)
252}
253
Hao Zhu76f0eb62018-09-15 12:38:33 -0400254ez_rep <- function(x, n) {
255 if (is.null(x)) return(NULL)
256 if (length(x) == 1) return(rep(x, n))
257 return(x)
258}
259
Hao Zhu32f43f72017-06-20 18:24:54 -0400260pdfTable_new_header_generator <- function(header_df, booktabs = FALSE,
Hao Zhu76f0eb62018-09-15 12:38:33 -0400261 bold, italic, monospace,
262 underline, strikeout, align,
Hao Zhub548aac2018-09-18 13:29:01 -0400263 color, background, font_size, angle,
Hao Zhu8b2126e2019-04-16 17:58:01 -0400264 line_sep, border_left, border_right) {
Hao Zhu76f0eb62018-09-15 12:38:33 -0400265 n <- nrow(header_df)
266 bold <- ez_rep(bold, n)
267 italic <- ez_rep(italic, n)
268 monospace <- ez_rep(monospace, n)
269 underline <- ez_rep(underline, n)
270 strikeout <- ez_rep(strikeout, n)
271 align <- ez_rep(align, n)
272 color <- ez_rep(color, n)
273 background <- ez_rep(background, n)
274 font_size <- ez_rep(font_size, n)
275 angle <- ez_rep(angle, n)
Hao Zhu8b2126e2019-04-16 17:58:01 -0400276 if (!booktabs & n != 1) {
martinschmelzerf43dcf52019-01-08 13:02:52 +0100277 align[1:(n - 1)] <- paste0(align[1:(n - 1)], "|")
Hao Zhuc1f38412017-02-23 12:13:48 -0500278 }
Hao Zhu8b2126e2019-04-16 17:58:01 -0400279 if (border_left) {
280 align[1] <- paste0("|", align[1])
281 }
282 if (border_right) {
283 align[n] <- paste0(align[n], "|")
284 }
285
Hao Zhu76f0eb62018-09-15 12:38:33 -0400286 header <- header_df$header
287 colspan <- header_df$colspan
288
289 header <- ifelse(bold, paste0('\\\\textbf\\{', header, '\\}'), header)
290 header <- ifelse(italic, paste0('\\\\em\\{', header, '\\}'), header)
291 header <- ifelse(monospace, paste0('\\\\ttfamily\\{', header, '\\}'), header)
292 header <- ifelse(underline, paste0('\\\\underline\\{', header, '\\}'), header)
293 header <- ifelse(strikeout, paste0('\\\\sout\\{', header, '\\}'), header)
294 if (!is.null(color)) {
295 color <- latex_color(color)
296 header <- paste0("\\\\textcolor", color, "\\{", header, "\\}")
297 }
298 if (!is.null(background)) {
299 background <- latex_color(background)
300 header <- paste0("\\\\cellcolor", background, "\\{", header, "\\}")
301 }
302 if (!is.null(font_size)) {
303 header <- paste0("\\\\bgroup\\\\fontsize\\{", font_size, "\\}\\{",
304 as.numeric(font_size) + 2,
305 "\\}\\\\selectfont ", header, "\\\\egroup\\{\\}")
306 }
307 if (!is.null(angle)) {
308 header <- paste0("\\\\rotatebox\\{", angle, "\\}\\{", header, "\\}")
309 }
310 header_items <- paste0(
311 '\\\\multicolumn\\{', colspan, '\\}\\{', align, '\\}\\{', header, '\\}'
312 )
313
Hao Zhuc1f38412017-02-23 12:13:48 -0500314 header_text <- paste(paste(header_items, collapse = " & "), "\\\\\\\\")
Hao Zhub548aac2018-09-18 13:29:01 -0400315 cline <- cline_gen(header_df, booktabs, line_sep)
Hao Zhu2ce42b92017-06-15 17:15:33 -0400316 return(c(header_text, cline))
317}
318
Hao Zhub548aac2018-09-18 13:29:01 -0400319cline_gen <- function(header_df, booktabs, line_sep) {
Hao Zhuc1f38412017-02-23 12:13:48 -0500320 cline_end <- cumsum(header_df$colspan)
321 cline_start <- c(0, cline_end) + 1
322 cline_start <- cline_start[-length(cline_start)]
Hao Zhub548aac2018-09-18 13:29:01 -0400323 cline_type <- switch(
324 booktabs + 1,
325 "\\\\cline{",
326 glue::glue("\\\\cmidrule(l{[line_sep]pt}r{[line_sep]pt}){",
327 .open = "[", .close = "]"))
Hao Zhuc1f38412017-02-23 12:13:48 -0500328 cline <- paste0(cline_type, cline_start, "-", cline_end, "}")
329 cline <- cline[trimws(header_df$header) != ""]
330 cline <- paste(cline, collapse = " ")
Hao Zhu2ce42b92017-06-15 17:15:33 -0400331 return(cline)
Hao Zhuc1f38412017-02-23 12:13:48 -0500332}
Hao Zhu2ce42b92017-06-15 17:15:33 -0400333
334