blob: 9827811020e2d263a6092891249f9208e5e43da5 [file] [log] [blame]
Hao Zhu62cdde52017-05-20 22:16:03 -04001#' Put a few rows of a table into one category
2#'
3#' @export
4group_rows <- function(kable_input, group_label, start_row, end_row) {
5 kable_format <- attr(kable_input, "format")
6 if (!kable_format %in% c("html", "latex")) {
7 message("Currently generic markdown table using pandoc is not supported.")
8 return(kable_input)
9 }
10 if (kable_format == "html") {
11 return(group_rows_html(kable_input, group_label, start_row, end_row))
12 }
13 if (kable_format == "latex") {
14 return(group_rows_latex(kable_input, group_label, start_row, end_row))
15 }
16}
17
18group_rows_html <- function(kable_input, group_label, start_row, end_row) {
19 if (!is.numeric(c(start_row, end_row))) {
20 stop("Start_row and end_row must be numeric position of rows (excluding",
21 "header rows and other group-title rows). ")
22 }
23 kable_attrs <- attributes(kable_input)
24 kable_xml <- read_xml(as.character(kable_input), options = "COMPACT")
25 kable_tbody <- xml_tpart(kable_xml, "tbody")
26
27 group_header_rows <- attr(kable_input, "group_header_rows")
28 group_seq <- seq(start_row, end_row)
29 if (!is.null(group_header_rows)) {
30 group_seq <- positions_corrector(group_seq, group_header_rows,
31 length(xml_children(kable_tbody)))
32 }
33
34 # Insert a group header row
35 starting_node <- xml_child(kable_tbody, group_seq[1])
36 kable_ncol <- length(xml_children(starting_node))
37 group_header_row_text <- paste0(
38 '<tr groupLength="', length(group_seq), '"><td colspan="',
39 kable_ncol, '"><strong>', group_label, "</strong></td></tr>"
40 )
41 group_header_row <- read_xml(group_header_row_text, options = "COMPACT")
42 xml_add_sibling(starting_node, group_header_row, .where = "before")
43
44 # add indentations to items
45 out <- structure(as.character(kable_xml), format = "html",
46 class = "knitr_kable")
47 attributes(out) <- kable_attrs
48 attr(out, "group_header_rows") <- c(attr(out, "group_header_rows"), group_seq[1])
49 out <- add_indent(out, positions = seq(start_row, end_row))
50 return(out)
51}