blob: d9a305c61cee031e4deef86463fcb586834e9ea0 [file] [log] [blame]
Hao Zhu3166f062017-06-26 07:51:46 -10001#' Collapse repeated rows to multirow cell
Hao Zhu2a87e8e2017-06-14 15:49:33 -04002#'
Hao Zhu8a160b12017-06-26 13:41:35 -10003#' @description Collapse same values in columns into multirow cells. This
4#' feature does similar things with `group_rows`. However, unlike `group_rows`,
5#' it analyzes existing columns, finds out rows that can be grouped together,
6#' and make them multirow cells. Note that if you want to use `column_spec` to
7#' specify column styles, you should use `column_spec` before `collapse_rows`.
8#'
9#' @param kable_input Output of `knitr::kable()` with `format` specified
10#' @param columns Numeric column positions where rows need to be collapsed.
11#'
Hao Zhu5a7689e2017-06-26 15:37:24 -100012#' @examples dt <- data.frame(a = c(1, 1, 2, 2), b = c("a", "a", "a", "b"))
13#' x <- knitr::kable(dt, "html")
14#' collapse_rows(x)
15#'
Hao Zhuf4b35292017-06-25 22:38:37 -100016#' @export
17collapse_rows <- function(kable_input, columns = NULL) {
18 # if (is.null(columns)) {
19 # stop("Please specify numeric positions of columns you want to collapse.")
20 # }
Hao Zhu2a87e8e2017-06-14 15:49:33 -040021 kable_format <- attr(kable_input, "format")
22 if (!kable_format %in% c("html", "latex")) {
23 message("Currently generic markdown table using pandoc is not supported.")
24 return(kable_input)
25 }
26 if (kable_format == "html") {
27 return(collapse_rows_html(kable_input, columns))
28 }
29 if (kable_format == "latex") {
30 return(collapse_rows_latex(kable_input, columns))
31 }
32}
33
34collapse_rows_html <- function(kable_input, columns) {
35 kable_attrs <- attributes(kable_input)
36 kable_xml <- read_xml(as.character(kable_input), options = "COMPACT")
37 kable_tbody <- xml_tpart(kable_xml, "tbody")
38
39 kable_dt <- rvest::html_table(xml2::read_html(as.character(kable_input)))[[1]]
Hao Zhuf4b35292017-06-25 22:38:37 -100040 if (is.null(columns)) {
41 columns <- seq(1, ncol(kable_dt))
42 }
Hao Zhu2a87e8e2017-06-14 15:49:33 -040043 kable_dt$row_id <- rownames(kable_dt)
44 collapse_matrix <- collapse_row_matrix(kable_dt, columns)
45
46 for (i in 1:nrow(collapse_matrix)) {
47 matrix_row <- collapse_matrix[i, ]
Hao Zhu3166f062017-06-26 07:51:46 -100048 target_row <- xml_child(kable_tbody, i)
49 row_node_rm_count <- 0
50 for (j in 1:length(matrix_row)) {
51 collapsing_col <- as.numeric(sub("x", "", names(matrix_row)[j])) -
52 row_node_rm_count
53 target_cell <- xml_child(target_row, collapsing_col)
54 if (matrix_row[j] == 0) {
55 xml_remove(target_cell)
56 row_node_rm_count <- row_node_rm_count + 1
57 } else if (matrix_row[j] != 1) {
58 xml_attr(target_cell, "rowspan") <- matrix_row[j]
59 xml_attr(target_cell, "style") <- paste0(
60 xml_attr(target_cell, "style"),
61 "vertical-align: middle !important;")
Hao Zhu2a87e8e2017-06-14 15:49:33 -040062 }
63 }
64 }
65
66 out <- structure(as.character(kable_xml), format = "html",
67 class = "knitr_kable")
68 attributes(out) <- kable_attrs
69 return(out)
70}
71
Hao Zhuf4b35292017-06-25 22:38:37 -100072collapse_row_matrix <- function(kable_dt, columns, html = T) {
73 if (html) {
74 column_block <- function(x) c(x, rep(0, x - 1))
75 } else {
76 column_block <- function(x) c(rep(0, x - 1), x)
77 }
78 mapping_matrix <- list()
79 for (i in columns) {
80 mapping_matrix[[paste0("x", i)]] <- unlist(lapply(
81 rle(kable_dt[, i])$length, column_block))
82 }
83 mapping_matrix <- data.frame(mapping_matrix)
84 return(mapping_matrix)
85}
86
Hao Zhu2a87e8e2017-06-14 15:49:33 -040087collapse_rows_latex <- function(kable_input, columns) {
Hao Zhuf4b35292017-06-25 22:38:37 -100088 table_info <- magic_mirror(kable_input)
89 if (is.null(columns)) {
90 columns <- seq(1, table_info$ncol)
91 }
92 if (!table_info$booktabs) {
93 warning("add_header_left only supports LaTeX table with booktabs. Please",
94 " use kable(..., booktabs = T) in your kable function.")
95 }
96 out <- as.character(kable_input)
97 contents <- table_info$contents
98 kable_dt <- kable_dt_latex(contents)
99 collapse_matrix <- collapse_row_matrix(kable_dt, columns, html = F)
100
101 new_kable_dt <- kable_dt
102 new_contents <- c()
103 for (j in seq(1:ncol(collapse_matrix))) {
104 column_align <- table_info$align_vector_origin[columns[j]]
105 column_width <- ifelse(
106 is.null(table_info$column_width[[paste0("column_", columns[j])]]),
107 "*", table_info$column_width[paste0("column_", columns[j])])
108 for (i in seq(1:nrow(collapse_matrix))) {
109 new_kable_dt[i, j] <- collapse_new_dt_item(
110 kable_dt[i, j], collapse_matrix[i, j], column_width, align = column_align
111 )
112 }
113 }
114 for (i in seq(1:nrow(collapse_matrix))) {
115 new_contents[i] <- paste0(new_kable_dt[i, ], collapse = " & ")
116 out <- sub(contents[i + 1], new_contents[i], out)
117 }
118
119 out <- structure(out, format = "latex", class = "knitr_kable")
120 table_info$collapse_rows <- TRUE
121 attr(out, "kable_meta") <- table_info
122 return(out)
123}
124
125kable_dt_latex <- function(x) {
126 data.frame(do.call(rbind, str_split(x[-1], " & ")), stringsAsFactors = FALSE)
127}
128
129collapse_new_dt_item <- function(x, span, width = NULL, align) {
130 if (span == 0) return("")
131 if (span == 1) return(x)
132 out <- paste0(
133 "\\\\multirow\\{", -span, "\\}\\{",
134 ifelse(is.null(width), "\\*", width),
135 "\\}\\{",
136 switch(align,
137 "l" = "\\\\raggedright\\\\arraybackslash ",
138 "c" = "\\\\centering\\\\arraybackslash ",
139 "r" = "\\\\raggedleft\\\\arraybackslash "),
140 x, "\\}"
141 )
142 return(out)
Hao Zhu2a87e8e2017-06-14 15:49:33 -0400143}