blob: 29ab6d71e225649927e185bc577ab988e90e9d15 [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()`
5#' function and adds an header row on top of it. This function can work with
6#' both `HTML` and `LaTeX` outputs
7#'
8#' @param kable_input Output of `knitr::kable()` with `format` specified
9#' @param header A (named) character vector with `colspan` as values. For
10#' example, `c(" " = 1, "title" = 2)` can be used to create a new header row
11#' for a 3-column table with "title" spanning across column 2 and 3. For
12#' convenience, when `colspan` equals to 1, users can drop the ` = 1` part.
13#' As a result, `c(" ", "title" = 2)` is the same as `c(" " = 1, "title" = 2)`.
14#'
Hao Zhu78e61222017-05-24 20:53:35 -040015#' @examples x <- knitr::kable(head(mtcars), "html")
16#' # Add a row of header with 3 columns on the top of the table. The column
17#' # span for the 2nd and 3rd one are 5 & 6.
18#' add_header_above(x, c(" ", "Group 1" = 5, "Group 2" = 6))
19#'
Hao Zhuc1f38412017-02-23 12:13:48 -050020#' @export
21add_header_above <- function(kable_input, header = NULL) {
22 kable_format <- attr(kable_input, "format")
23 if (!kable_format %in% c("html", "latex")) {
24 stop("Please specify output format in your kable function. Currently ",
25 "generic markdown table using pandoc is not supported.")
26 }
27 if (kable_format == "html") {
28 return(htmlTable_add_header_above(kable_input, header))
29 }
30 if (kable_format == "latex") {
31 return(pdfTable_add_header_above(kable_input, header))
32 }
33}
34
35# HTML
36htmlTable_add_header_above <- function(kable_input, header = NULL) {
37 if (is.null(header)) return(kable_input)
Hao Zhu909ea382017-06-12 15:43:47 -040038 kable_attrs <- attributes(kable_input)
Hao Zhuc1f38412017-02-23 12:13:48 -050039 kable_xml <- read_xml(as.character(kable_input), options = c("COMPACT"))
Hao Zhu62cdde52017-05-20 22:16:03 -040040 kable_xml_thead <- xml_tpart(kable_xml, "thead")
Hao Zhuc1f38412017-02-23 12:13:48 -050041
42 header <- standardize_header_input(header)
43
44 header_rows <- xml_children(kable_xml_thead)
45 bottom_header_row <- header_rows[[length(header_rows)]]
46 kable_ncol <- length(xml_children(bottom_header_row))
47 if (sum(header$colspan) != kable_ncol) {
48 stop("The new header row you provided has a different total number of ",
49 "columns with the original kable output.")
50 }
51
52 new_header_row <- htmlTable_new_header_generator(header)
53 xml_add_child(kable_xml_thead, new_header_row, .where = 0)
Hao Zhu9b45a182017-02-27 18:17:46 -050054 out <- structure(as.character(kable_xml), format = "html",
55 class = "knitr_kable")
Hao Zhu909ea382017-06-12 15:43:47 -040056 attributes(out) <- kable_attrs
Hao Zhu6a076462017-03-01 12:59:01 -050057 return(out)
Hao Zhuc1f38412017-02-23 12:13:48 -050058}
59
60standardize_header_input <- function(header) {
61 header_names <- names(header)
62
63 if (is.null(header_names)) {
64 return(data.frame(header = header, colspan = 1, row.names = NULL))
65 }
66
67 names(header)[header_names == ""] <- header[header_names == ""]
68 header[header_names == ""] <- 1
69 header_names <- names(header)
70 header <- as.numeric(header)
71 names(header) <- header_names
72 return(data.frame(header = names(header), colspan = header, row.names = NULL))
73}
74
75htmlTable_new_header_generator <- function(header_df) {
76 header_items <- apply(header_df, 1, function(x) {
Hao Zhuacc7ceb2017-05-26 10:50:25 -070077 if (trimws(x[1]) == "") {
Hao Zhu6d2faa12017-05-24 02:16:45 -040078 paste0('<th style="border-bottom:hidden"></th>')
79 } else {
Hao Zhuacc7ceb2017-05-26 10:50:25 -070080 paste0('<th style="text-align:center; border-bottom:hidden; ',
81 'padding-bottom:0; padding-left:3px;padding-right:3px;" colspan="',
Hao Zhu71e378a2017-05-26 11:00:21 -070082 x[2], '"><div style="border-bottom: 1px solid #ddd;padding-bottom: 5px;">',
Hao Zhuacc7ceb2017-05-26 10:50:25 -070083 x[1], '</div></th>')
Hao Zhu6d2faa12017-05-24 02:16:45 -040084 }
Hao Zhuc1f38412017-02-23 12:13:48 -050085 })
86 header_text <- paste(c("<tr>", header_items, "</tr>"), collapse = "")
87 header_xml <- read_xml(header_text, options = c("COMPACT"))
88 return(header_xml)
89}
90
91# Add an extra header row above the current header in a LaTeX table ------
92pdfTable_add_header_above <- function(kable_input, header = NULL) {
93 table_info <- magic_mirror(kable_input)
94 header <- standardize_header_input(header)
95 hline_type <- switch(table_info$booktabs + 1, "\\\\hline", "\\\\toprule")
96 out <- sub(hline_type,
97 paste0(hline_type, "\n",
98 pdfTable_new_header_generator(header, table_info$booktabs)),
99 as.character(kable_input))
100 out <- structure(out, format = "latex", class = "knitr_kable")
Hao Zhu9b45a182017-02-27 18:17:46 -0500101 attr(out, "original_kable_meta") <- table_info
Hao Zhuc1f38412017-02-23 12:13:48 -0500102 return(out)
103}
104
105pdfTable_new_header_generator <- function(header_df, booktabs = F) {
106 if (booktabs) {
107 header_df$align <- "c"
108 } else {
109 header_df$align <- "|c|"
110 header_df$align[1] <- "c|"
111 header_df$align[nrow(header_df)] <- "|c"
112 }
113 header_items <- apply(header_df, 1, function(x) {
114 # if(x[2] == 1) return(x[1])
115 paste0('\\\\multicolumn{', x[2], '}{', x[3], '}{', x[1], "}")
116 })
117 header_text <- paste(paste(header_items, collapse = " & "), "\\\\\\\\")
118 cline_end <- cumsum(header_df$colspan)
119 cline_start <- c(0, cline_end) + 1
120 cline_start <- cline_start[-length(cline_start)]
Hao Zhuc05e1812017-02-25 01:45:35 -0500121 cline_type <- switch(booktabs + 1,
122 "\\\\cline{",
123 "\\\\cmidrule(l{2pt}r{2pt}){")
Hao Zhuc1f38412017-02-23 12:13:48 -0500124 cline <- paste0(cline_type, cline_start, "-", cline_end, "}")
125 cline <- cline[trimws(header_df$header) != ""]
126 cline <- paste(cline, collapse = " ")
127 header_text <- paste(header_text, cline)
128 return(header_text)
129}