blob: 961601ebdeaa9e8c651cf47fa59eb3a3e660d455 [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.
Hao Zhu5dd3e282018-05-20 18:39:48 -040011#' @param valign Select from "top"(default), "middle", "bottom"
Hao Zhu12b0ade2018-01-13 16:19:58 -050012#' @param latex_hline Option controlling the behavior of adding hlines to table.
georgeguieaeb0cd2018-03-30 17:39:46 -050013#' Choose from `full`, `major`, `none`, `custom`.
14#' @param custom_latex_hline Numeric column positions whose collapsed rows will
15#' be separated by hlines.
16#' @param row_group_label_position Option controlling positions of row group
17#' labels. Choose from `identity`, `stack`.
18#' @param row_group_label_fonts A list of arguments that can be supplied to
19#' group_rows function to format the row group label when
20#' `row_group_label_position` is `stack`
21#' @param headers_to_remove Numeric column positions where headers should be
22#' removed when they are stacked.
Hao Zhu8a160b12017-06-26 13:41:35 -100023#'
Hao Zhu5a7689e2017-06-26 15:37:24 -100024#' @examples dt <- data.frame(a = c(1, 1, 2, 2), b = c("a", "a", "a", "b"))
25#' x <- knitr::kable(dt, "html")
26#' collapse_rows(x)
27#'
Hao Zhuf4b35292017-06-25 22:38:37 -100028#' @export
Hao Zhu12b0ade2018-01-13 16:19:58 -050029collapse_rows <- function(kable_input, columns = NULL,
Hao Zhu5dd3e282018-05-20 18:39:48 -040030 valign = c("top", "middle", "bottom"),
georgeguieaeb0cd2018-03-30 17:39:46 -050031 latex_hline = c("full", "major", "none", "custom"),
32 row_group_label_position = c('identity', 'stack'),
33 custom_latex_hline = NULL,
34 row_group_label_fonts = NULL,
35 headers_to_remove = NULL) {
Hao Zhu2a87e8e2017-06-14 15:49:33 -040036 kable_format <- attr(kable_input, "format")
37 if (!kable_format %in% c("html", "latex")) {
Hao Zhu401ebd82018-01-14 17:10:20 -050038 warning("Please specify format in kable. kableExtra can customize either ",
39 "HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ",
40 "for details.")
Hao Zhu2a87e8e2017-06-14 15:49:33 -040041 return(kable_input)
42 }
Hao Zhu5dd3e282018-05-20 18:39:48 -040043 valign <- match.arg(valign, c("top", "middle", "bottom"))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040044 if (kable_format == "html") {
Hao Zhu5dd3e282018-05-20 18:39:48 -040045 return(collapse_rows_html(kable_input, columns, valign))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040046 }
47 if (kable_format == "latex") {
georgeguieaeb0cd2018-03-30 17:39:46 -050048 latex_hline <- match.arg(latex_hline, c("full", "major", "none", "custom"))
49 row_group_label_position <- match.arg(row_group_label_position,
50 c('identity', 'stack'))
Hao Zhu5dd3e282018-05-20 18:39:48 -040051 return(collapse_rows_latex(kable_input, columns, latex_hline, valign,
georgeguieaeb0cd2018-03-30 17:39:46 -050052 row_group_label_position, row_group_label_fonts, custom_latex_hline,
53 headers_to_remove))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040054 }
55}
56
Hao Zhu5dd3e282018-05-20 18:39:48 -040057collapse_rows_html <- function(kable_input, columns, valign) {
Hao Zhu2a87e8e2017-06-14 15:49:33 -040058 kable_attrs <- attributes(kable_input)
Hao Zhu558c72f2017-07-24 15:12:00 -040059 kable_xml <- read_kable_as_xml(kable_input)
Hao Zhu2a87e8e2017-06-14 15:49:33 -040060 kable_tbody <- xml_tpart(kable_xml, "tbody")
61
62 kable_dt <- rvest::html_table(xml2::read_html(as.character(kable_input)))[[1]]
Hao Zhuf4b35292017-06-25 22:38:37 -100063 if (is.null(columns)) {
64 columns <- seq(1, ncol(kable_dt))
65 }
Hao Zhu23456762018-03-26 12:30:10 -040066 if (!is.null(kable_attrs$header_above)) {
67 kable_dt_col_names <- unlist(kable_dt[kable_attrs$header_above, ])
68 kable_dt <- kable_dt[-(1:kable_attrs$header_above),]
69 names(kable_dt) <- kable_dt_col_names
70 }
71 kable_dt$row_id <- seq(nrow(kable_dt))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040072 collapse_matrix <- collapse_row_matrix(kable_dt, columns)
73
74 for (i in 1:nrow(collapse_matrix)) {
75 matrix_row <- collapse_matrix[i, ]
Hao Zhu38cdcdb2017-06-27 09:08:30 -100076 names(matrix_row) <- names(collapse_matrix)
Hao Zhu3166f062017-06-26 07:51:46 -100077 target_row <- xml_child(kable_tbody, i)
78 row_node_rm_count <- 0
79 for (j in 1:length(matrix_row)) {
80 collapsing_col <- as.numeric(sub("x", "", names(matrix_row)[j])) -
81 row_node_rm_count
82 target_cell <- xml_child(target_row, collapsing_col)
83 if (matrix_row[j] == 0) {
84 xml_remove(target_cell)
85 row_node_rm_count <- row_node_rm_count + 1
86 } else if (matrix_row[j] != 1) {
87 xml_attr(target_cell, "rowspan") <- matrix_row[j]
88 xml_attr(target_cell, "style") <- paste0(
89 xml_attr(target_cell, "style"),
Hao Zhu5dd3e282018-05-20 18:39:48 -040090 "vertical-align: ", valign, " !important;")
Hao Zhu2a87e8e2017-06-14 15:49:33 -040091 }
92 }
93 }
94
Hao Zhuf2dfd142017-07-24 14:43:28 -040095 out <- as_kable_xml(kable_xml)
Hao Zhu2a87e8e2017-06-14 15:49:33 -040096 attributes(out) <- kable_attrs
Hao Zhuf2100832018-01-11 16:20:29 -050097 if (!"kableExtra" %in% class(out)) class(out) <- c("kableExtra", class(out))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040098 return(out)
99}
100
Hao Zhuf4b35292017-06-25 22:38:37 -1000101collapse_row_matrix <- function(kable_dt, columns, html = T) {
102 if (html) {
103 column_block <- function(x) c(x, rep(0, x - 1))
104 } else {
105 column_block <- function(x) c(rep(0, x - 1), x)
106 }
107 mapping_matrix <- list()
108 for (i in columns) {
109 mapping_matrix[[paste0("x", i)]] <- unlist(lapply(
110 rle(kable_dt[, i])$length, column_block))
111 }
112 mapping_matrix <- data.frame(mapping_matrix)
113 return(mapping_matrix)
114}
115
Hao Zhu5dd3e282018-05-20 18:39:48 -0400116collapse_rows_latex <- function(kable_input, columns, latex_hline, valign,
georgeguieaeb0cd2018-03-30 17:39:46 -0500117 row_group_label_position, row_group_label_fonts,
118 custom_latex_hline, headers_to_remove) {
Hao Zhuf4b35292017-06-25 22:38:37 -1000119 table_info <- magic_mirror(kable_input)
Hao Zhu3fc0e882018-04-03 16:06:41 -0400120 out <- solve_enc(kable_input)
Hao Zhu064990d2017-10-17 18:08:42 -0400121
Hao Zhu5dd3e282018-05-20 18:39:48 -0400122 valign <- switch(
123 valign,
124 top = "\\[t\\]",
125 middle = "",
126 bottom = "\\[b\\]"
127 )
128
Hao Zhuf4b35292017-06-25 22:38:37 -1000129 if (is.null(columns)) {
130 columns <- seq(1, table_info$ncol)
131 }
Hao Zhu064990d2017-10-17 18:08:42 -0400132
Hao Zhuf4b35292017-06-25 22:38:37 -1000133 contents <- table_info$contents
134 kable_dt <- kable_dt_latex(contents)
georgeguieaeb0cd2018-03-30 17:39:46 -0500135
136 collapse_matrix_rev <- collapse_row_matrix(kable_dt, columns, html = TRUE)
Hao Zhu01b15b82018-01-12 17:48:21 -0500137 collapse_matrix <- collapse_row_matrix(kable_dt, columns, html = FALSE)
Hao Zhuf4b35292017-06-25 22:38:37 -1000138
139 new_kable_dt <- kable_dt
Hao Zhuf4b35292017-06-25 22:38:37 -1000140 for (j in seq(1:ncol(collapse_matrix))) {
141 column_align <- table_info$align_vector_origin[columns[j]]
142 column_width <- ifelse(
143 is.null(table_info$column_width[[paste0("column_", columns[j])]]),
144 "*", table_info$column_width[paste0("column_", columns[j])])
145 for (i in seq(1:nrow(collapse_matrix))) {
georgeguieaeb0cd2018-03-30 17:39:46 -0500146 if(row_group_label_position == 'stack'){
147 if(j < ncol(collapse_matrix)|(collapse_matrix_rev[i, j] == 0)){
148 new_kable_dt[i, j] <- ''
149 }
150 } else {
151 new_kable_dt[i, j] <- collapse_new_dt_item(
Hao Zhu5dd3e282018-05-20 18:39:48 -0400152 kable_dt[i, j], collapse_matrix[i, j], column_width,
153 align = column_align, valign = valign
georgeguieaeb0cd2018-03-30 17:39:46 -0500154 )
155 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000156 }
157 }
Hao Zhu654c91f2017-07-03 14:03:34 -0400158
159 midrule_matrix <- collapse_row_matrix(kable_dt, seq(1, table_info$ncol),
160 html = F)
161 midrule_matrix[setdiff(seq(1, table_info$ncol), columns)] <- 1
162
163 ex_bottom <- length(contents) - 1
164 contents[2:ex_bottom] <- paste0(contents[2:ex_bottom], "\\\\\\\\")
165 if (!table_info$booktabs) {
166 contents[2:ex_bottom] <- paste0(contents[2:ex_bottom], "\n\\\\hline")
167 }
Hao Zhu01b15b82018-01-12 17:48:21 -0500168
169 new_contents <- c()
georgeguieaeb0cd2018-03-30 17:39:46 -0500170 if(row_group_label_position == 'stack'){
171 if(is.null(headers_to_remove)) headers_to_remove <- head(columns, -1)
172 table_info$colnames[headers_to_remove] <- ''
173 new_header <- paste(table_info$colnames, collapse = ' & ')
174 out <- sub(contents[1], new_header, out)
175 table_info$contents[1] <- new_header
176 }
177 if(latex_hline == 'custom' & is.null(custom_latex_hline)){
178 if(row_group_label_position == 'stack'){
179 custom_latex_hline = 1:2
180 } else {
181 custom_latex_hline = 1
182 }
183 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000184 for (i in seq(1:nrow(collapse_matrix))) {
185 new_contents[i] <- paste0(new_kable_dt[i, ], collapse = " & ")
Hao Zhu12b0ade2018-01-13 16:19:58 -0500186 table_info$contents[i + 1] <- new_contents[i]
Hao Zhu654c91f2017-07-03 14:03:34 -0400187 if (i != nrow(collapse_matrix)) {
Hao Zhu12b0ade2018-01-13 16:19:58 -0500188 row_midrule <- switch(
189 latex_hline,
190 "none" = "",
191 "full" = midline_groups(which(as.numeric(midrule_matrix[i, ]) > 0),
192 table_info$booktabs),
193 "major" = ifelse(
194 sum(as.numeric(midrule_matrix[i, ]) > 0) == ncol(midrule_matrix),
195 midline_groups(which(as.numeric(midrule_matrix[i, ]) > 0),
196 table_info$booktabs),
197 ""
georgeguieaeb0cd2018-03-30 17:39:46 -0500198 ),
199 "custom" = ifelse(
200 sum(as.numeric(midrule_matrix[i, custom_latex_hline])) > 0,
201 midline_groups(which(as.numeric(midrule_matrix[i, ]) > 0),
202 table_info$booktabs),
203 ""
204 )
Hao Zhu12b0ade2018-01-13 16:19:58 -0500205 )
Hao Zhu654c91f2017-07-03 14:03:34 -0400206 new_contents[i] <- paste0(new_contents[i], "\\\\\\\\\n", row_midrule)
207 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000208 out <- sub(contents[i + 1], new_contents[i], out)
209 }
Hao Zhu8f202992017-07-15 02:20:18 -0400210 out <- gsub("\\\\addlinespace\n", "", out)
Hao Zhuf4b35292017-06-25 22:38:37 -1000211
212 out <- structure(out, format = "latex", class = "knitr_kable")
213 table_info$collapse_rows <- TRUE
214 attr(out, "kable_meta") <- table_info
georgeguieaeb0cd2018-03-30 17:39:46 -0500215 if(row_group_label_position == 'stack'){
216 group_row_index_list <- collapse_rows_index(kable_dt, head(columns, -1))
217 out <- collapse_rows_latex_stack(out, group_row_index_list, row_group_label_fonts)
218 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000219 return(out)
220}
221
222kable_dt_latex <- function(x) {
223 data.frame(do.call(rbind, str_split(x[-1], " & ")), stringsAsFactors = FALSE)
224}
225
Hao Zhu5dd3e282018-05-20 18:39:48 -0400226collapse_new_dt_item <- function(x, span, width = NULL, align, valign) {
Hao Zhuf4b35292017-06-25 22:38:37 -1000227 if (span == 0) return("")
228 if (span == 1) return(x)
229 out <- paste0(
Hao Zhu5dd3e282018-05-20 18:39:48 -0400230 "\\\\multirow", valign, "\\{", -span, "\\}\\{",
Hao Zhuf4b35292017-06-25 22:38:37 -1000231 ifelse(is.null(width), "\\*", width),
232 "\\}\\{",
233 switch(align,
234 "l" = "\\\\raggedright\\\\arraybackslash ",
235 "c" = "\\\\centering\\\\arraybackslash ",
236 "r" = "\\\\raggedleft\\\\arraybackslash "),
237 x, "\\}"
238 )
239 return(out)
Hao Zhu2a87e8e2017-06-14 15:49:33 -0400240}
Hao Zhu654c91f2017-07-03 14:03:34 -0400241
242midline_groups <- function(x, booktabs = T) {
243 diffs <- c(1, diff(x))
244 start_indexes <- c(1, which(diffs > 1))
Hao Zhu12b0ade2018-01-13 16:19:58 -0500245 end_indexes <- c(start_indexes - 1, length(x))
Hao Zhu654c91f2017-07-03 14:03:34 -0400246 ranges <- paste0(x[start_indexes], "-", x[end_indexes])
247 if (booktabs) {
248 out <- paste0("\\\\cmidrule{", ranges, "}")
249 } else {
250 out <- paste0("\\\\cline{", ranges, "}")
251 }
252 out <- paste0(out, collapse = "\n")
253 return(out)
254}
georgeguieaeb0cd2018-03-30 17:39:46 -0500255
256
257collapse_rows_index <- function(kable_dt, columns) {
258 format_to_row_index <- function(x){
259 x = rle(x)
260 out = x$lengths
261 names(out) = x$values
262 out
263 }
264 group_rows_index_list <- lapply(columns, function(x) {
265 format_to_row_index(kable_dt[, x])
266 })
267 return(group_rows_index_list)
268}
269
270
271collapse_rows_latex_stack <- function(kable_input, group_row_index_list,
272 row_group_label_fonts){
273 merge_lists <- function(default_list, updated_list){
274 for(x in names(updated_list)){
275 default_list[[x]] <- updated_list[[x]]
276 }
277 return(default_list)
278 }
279 default_font_list <- list(
280 list(bold = T, italic = F),
281 list(bold = F, italic = T),
282 list(bold = F, italic = F)
283 )
284 n_default_fonts = length(default_font_list)
285 n_supplied_fonts = length(row_group_label_fonts)
286 group_row_font_list <- list()
287 out <- kable_input
288 for(i in 1:length(group_row_index_list)){
289 if(i > n_default_fonts){
290 group_row_args <- default_font_list[[n_default_fonts]]
291 } else {
292 group_row_args <- default_font_list[[i]]
293 }
294 if(i <= n_supplied_fonts){
295 group_row_args <- merge_lists(group_row_args, row_group_label_fonts[[i]])
296 }
297 group_row_args <- merge_lists(
298 list(kable_input = out, index = group_row_index_list[[i]]),
299 group_row_args)
300 out <- do.call(group_rows, group_row_args)
301 }
302 return(out)
303}