blob: d45fe22bc68504dae309ef4e09754522ce6f0ac5 [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
Hao Zhu5e2528e2020-08-03 09:16:34 -040010#' @param columns A numeric value or vector indicating in which column(s) rows
Jakob Richteraebd8292018-10-31 16:27:29 +010011#' need to be collapsed.
Hao Zhuec169362018-05-21 01:05:29 -040012#' @param valign Select from "top", "middle"(default), "bottom". The reason why
13#' "top" is not default is that the multirow package on CRAN win-builder is
14#' not up to date.
Hao Zhu12b0ade2018-01-13 16:19:58 -050015#' @param latex_hline Option controlling the behavior of adding hlines to table.
georgeguieaeb0cd2018-03-30 17:39:46 -050016#' Choose from `full`, `major`, `none`, `custom`.
17#' @param custom_latex_hline Numeric column positions whose collapsed rows will
18#' be separated by hlines.
19#' @param row_group_label_position Option controlling positions of row group
20#' labels. Choose from `identity`, `stack`.
21#' @param row_group_label_fonts A list of arguments that can be supplied to
22#' group_rows function to format the row group label when
23#' `row_group_label_position` is `stack`
24#' @param headers_to_remove Numeric column positions where headers should be
25#' removed when they are stacked.
Hao Zhuc9858942020-08-11 21:41:09 -040026#' @param target If multiple columns are selected to do collapsing and a target
27#' column is specified, this target column will be used to collapse other
28#' columns based on the groups of this target column.
29#' @param col_names T/F. A LaTeX specific option. If you set `col.names` be
30#' `NULL` in your `kable` call, you need to set this option false to let
31#' everything work properly.
Hao Zhu8a160b12017-06-26 13:41:35 -100032#'
Hao Zhu5a7689e2017-06-26 15:37:24 -100033#' @examples dt <- data.frame(a = c(1, 1, 2, 2), b = c("a", "a", "a", "b"))
34#' x <- knitr::kable(dt, "html")
35#' collapse_rows(x)
36#'
Hao Zhuf4b35292017-06-25 22:38:37 -100037#' @export
Hao Zhu12b0ade2018-01-13 16:19:58 -050038collapse_rows <- function(kable_input, columns = NULL,
Hao Zhuec169362018-05-21 01:05:29 -040039 valign = c("middle", "top", "bottom"),
georgeguieaeb0cd2018-03-30 17:39:46 -050040 latex_hline = c("full", "major", "none", "custom"),
41 row_group_label_position = c('identity', 'stack'),
42 custom_latex_hline = NULL,
43 row_group_label_fonts = NULL,
Hao Zhu5e2528e2020-08-03 09:16:34 -040044 headers_to_remove = NULL,
Hao Zhuc9858942020-08-11 21:41:09 -040045 target = NULL,
46 col_names = TRUE) {
Hao Zhu2a87e8e2017-06-14 15:49:33 -040047 kable_format <- attr(kable_input, "format")
48 if (!kable_format %in% c("html", "latex")) {
Hao Zhu401ebd82018-01-14 17:10:20 -050049 warning("Please specify format in kable. kableExtra can customize either ",
50 "HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ",
51 "for details.")
Hao Zhu2a87e8e2017-06-14 15:49:33 -040052 return(kable_input)
53 }
Hao Zhuec169362018-05-21 01:05:29 -040054 valign <- match.arg(valign, c("middle", "top", "bottom"))
Hao Zhu5e2528e2020-08-03 09:16:34 -040055 if (!is.null(target)) {
56 if (length(target) > 1 && is.integer(target)) {
57 stop("target can only be a length 1 integer")
58 }
59 }
Hao Zhu2a87e8e2017-06-14 15:49:33 -040060 if (kable_format == "html") {
Hao Zhu5e2528e2020-08-03 09:16:34 -040061 return(collapse_rows_html(kable_input, columns, valign, target))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040062 }
63 if (kable_format == "latex") {
georgeguieaeb0cd2018-03-30 17:39:46 -050064 latex_hline <- match.arg(latex_hline, c("full", "major", "none", "custom"))
65 row_group_label_position <- match.arg(row_group_label_position,
66 c('identity', 'stack'))
Hao Zhu5dd3e282018-05-20 18:39:48 -040067 return(collapse_rows_latex(kable_input, columns, latex_hline, valign,
georgeguieaeb0cd2018-03-30 17:39:46 -050068 row_group_label_position, row_group_label_fonts, custom_latex_hline,
Hao Zhua9c7f032020-08-11 22:18:30 -040069 headers_to_remove, target, col_names))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040070 }
71}
72
Hao Zhu5e2528e2020-08-03 09:16:34 -040073collapse_rows_html <- function(kable_input, columns, valign, target) {
Hao Zhu2a87e8e2017-06-14 15:49:33 -040074 kable_attrs <- attributes(kable_input)
Hao Zhu5e2528e2020-08-03 09:16:34 -040075 kable_xml <- kable_as_xml(kable_input)
Hao Zhu2a87e8e2017-06-14 15:49:33 -040076 kable_tbody <- xml_tpart(kable_xml, "tbody")
77
78 kable_dt <- rvest::html_table(xml2::read_html(as.character(kable_input)))[[1]]
Hao Zhuf4b35292017-06-25 22:38:37 -100079 if (is.null(columns)) {
80 columns <- seq(1, ncol(kable_dt))
81 }
Hao Zhu5e2528e2020-08-03 09:16:34 -040082 if (!is.null(target)) {
83 if (!target %in% columns) {
84 stop("target has to be within the range of columns")
85 }
86 }
Hao Zhu23456762018-03-26 12:30:10 -040087 if (!is.null(kable_attrs$header_above)) {
88 kable_dt_col_names <- unlist(kable_dt[kable_attrs$header_above, ])
89 kable_dt <- kable_dt[-(1:kable_attrs$header_above),]
90 names(kable_dt) <- kable_dt_col_names
91 }
Hao Zhu5e2528e2020-08-03 09:16:34 -040092 collapse_matrix <- collapse_row_matrix(kable_dt, columns, target = target)
Hao Zhu2a87e8e2017-06-14 15:49:33 -040093
94 for (i in 1:nrow(collapse_matrix)) {
95 matrix_row <- collapse_matrix[i, ]
Hao Zhu38cdcdb2017-06-27 09:08:30 -100096 names(matrix_row) <- names(collapse_matrix)
Hao Zhu3166f062017-06-26 07:51:46 -100097 target_row <- xml_child(kable_tbody, i)
98 row_node_rm_count <- 0
99 for (j in 1:length(matrix_row)) {
100 collapsing_col <- as.numeric(sub("x", "", names(matrix_row)[j])) -
101 row_node_rm_count
102 target_cell <- xml_child(target_row, collapsing_col)
103 if (matrix_row[j] == 0) {
104 xml_remove(target_cell)
105 row_node_rm_count <- row_node_rm_count + 1
106 } else if (matrix_row[j] != 1) {
107 xml_attr(target_cell, "rowspan") <- matrix_row[j]
108 xml_attr(target_cell, "style") <- paste0(
109 xml_attr(target_cell, "style"),
Hao Zhu5dd3e282018-05-20 18:39:48 -0400110 "vertical-align: ", valign, " !important;")
Hao Zhu2a87e8e2017-06-14 15:49:33 -0400111 }
112 }
113 }
114
Hao Zhuf2dfd142017-07-24 14:43:28 -0400115 out <- as_kable_xml(kable_xml)
Hao Zhufdff6f42020-08-09 14:38:10 -0400116 kable_attrs$collapse_matrix <- collapse_matrix
Hao Zhu2a87e8e2017-06-14 15:49:33 -0400117 attributes(out) <- kable_attrs
Hao Zhuf2100832018-01-11 16:20:29 -0500118 if (!"kableExtra" %in% class(out)) class(out) <- c("kableExtra", class(out))
Hao Zhu2a87e8e2017-06-14 15:49:33 -0400119 return(out)
120}
121
Hao Zhu5e2528e2020-08-03 09:16:34 -0400122split_factor <- function(x) {
123 group_idx <- seq(1, length(x))
124 return(factor(unlist(lapply(group_idx, function(i) {rep(i, x[i])}))))
125}
126
127collapse_row_matrix <- function(kable_dt, columns, html = T, target = NULL) {
Hao Zhuf4b35292017-06-25 22:38:37 -1000128 if (html) {
129 column_block <- function(x) c(x, rep(0, x - 1))
130 } else {
131 column_block <- function(x) c(rep(0, x - 1), x)
132 }
133 mapping_matrix <- list()
Hao Zhu5e2528e2020-08-03 09:16:34 -0400134 if (is.null(target)) {
135 for (i in columns) {
136 mapping_matrix[[paste0("x", i)]] <- unlist(lapply(
137 rle(kable_dt[, i])$lengths, column_block))
138 }
139 } else {
140 target_group = split_factor(rle(kable_dt[, target])$lengths)
141 for (i in columns) {
142 column_split = split(kable_dt[, i], target_group)
143 mapping_matrix[[paste0("x", i)]] <- unlist(lapply(
144 column_split, function(sp) {
145 lapply(rle(sp)$length, column_block)
146 }))
147 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000148 }
Hao Zhu5e2528e2020-08-03 09:16:34 -0400149
Hao Zhuf4b35292017-06-25 22:38:37 -1000150 mapping_matrix <- data.frame(mapping_matrix)
151 return(mapping_matrix)
152}
153
Hao Zhu5dd3e282018-05-20 18:39:48 -0400154collapse_rows_latex <- function(kable_input, columns, latex_hline, valign,
georgeguieaeb0cd2018-03-30 17:39:46 -0500155 row_group_label_position, row_group_label_fonts,
Hao Zhuc9858942020-08-11 21:41:09 -0400156 custom_latex_hline, headers_to_remove, target,
157 col_names) {
Hao Zhuf4b35292017-06-25 22:38:37 -1000158 table_info <- magic_mirror(kable_input)
Hao Zhu3fc0e882018-04-03 16:06:41 -0400159 out <- solve_enc(kable_input)
Hao Zhu064990d2017-10-17 18:08:42 -0400160
Hao Zhu5dd3e282018-05-20 18:39:48 -0400161 valign <- switch(
162 valign,
163 top = "\\[t\\]",
164 middle = "",
165 bottom = "\\[b\\]"
166 )
167
Hao Zhuf4b35292017-06-25 22:38:37 -1000168 if (is.null(columns)) {
169 columns <- seq(1, table_info$ncol)
170 }
Hao Zhu064990d2017-10-17 18:08:42 -0400171
Hao Zhuf4b35292017-06-25 22:38:37 -1000172 contents <- table_info$contents
Hao Zhuc9858942020-08-11 21:41:09 -0400173 kable_dt <- kable_dt_latex(contents, col_names)
georgeguieaeb0cd2018-03-30 17:39:46 -0500174
Hao Zhuaa424412020-08-03 09:21:46 -0400175 collapse_matrix_rev <- collapse_row_matrix(kable_dt, columns, html = TRUE,
176 target)
177 collapse_matrix <- collapse_row_matrix(kable_dt, columns, html = FALSE,
178 target)
Hao Zhuf4b35292017-06-25 22:38:37 -1000179
180 new_kable_dt <- kable_dt
Jakob Richteraebd8292018-10-31 16:27:29 +0100181 for (j in seq_along(columns)) {
Hao Zhuf4b35292017-06-25 22:38:37 -1000182 column_align <- table_info$align_vector_origin[columns[j]]
183 column_width <- ifelse(
184 is.null(table_info$column_width[[paste0("column_", columns[j])]]),
185 "*", table_info$column_width[paste0("column_", columns[j])])
186 for (i in seq(1:nrow(collapse_matrix))) {
georgeguieaeb0cd2018-03-30 17:39:46 -0500187 if(row_group_label_position == 'stack'){
Jakob Richteraebd8292018-10-31 16:27:29 +0100188 if(columns[j] < ncol(collapse_matrix) || collapse_matrix_rev[i, j] == 0){
189 new_kable_dt[i, columns[j]] <- ''
georgeguieaeb0cd2018-03-30 17:39:46 -0500190 }
191 } else {
Jakob Richteraebd8292018-10-31 16:27:29 +0100192 new_kable_dt[i, columns[j]] <- collapse_new_dt_item(
193 kable_dt[i, columns[j]], collapse_matrix[i, j], column_width,
Hao Zhu5dd3e282018-05-20 18:39:48 -0400194 align = column_align, valign = valign
georgeguieaeb0cd2018-03-30 17:39:46 -0500195 )
196 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000197 }
198 }
Hao Zhu654c91f2017-07-03 14:03:34 -0400199
200 midrule_matrix <- collapse_row_matrix(kable_dt, seq(1, table_info$ncol),
Hao Zhuaa424412020-08-03 09:21:46 -0400201 html = FALSE, target)
Hao Zhu654c91f2017-07-03 14:03:34 -0400202 midrule_matrix[setdiff(seq(1, table_info$ncol), columns)] <- 1
203
204 ex_bottom <- length(contents) - 1
205 contents[2:ex_bottom] <- paste0(contents[2:ex_bottom], "\\\\\\\\")
206 if (!table_info$booktabs) {
207 contents[2:ex_bottom] <- paste0(contents[2:ex_bottom], "\n\\\\hline")
208 }
Hao Zhu01b15b82018-01-12 17:48:21 -0500209
210 new_contents <- c()
georgeguieaeb0cd2018-03-30 17:39:46 -0500211 if(row_group_label_position == 'stack'){
212 if(is.null(headers_to_remove)) headers_to_remove <- head(columns, -1)
213 table_info$colnames[headers_to_remove] <- ''
214 new_header <- paste(table_info$colnames, collapse = ' & ')
215 out <- sub(contents[1], new_header, out)
216 table_info$contents[1] <- new_header
217 }
218 if(latex_hline == 'custom' & is.null(custom_latex_hline)){
219 if(row_group_label_position == 'stack'){
220 custom_latex_hline = 1:2
221 } else {
222 custom_latex_hline = 1
223 }
224 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000225 for (i in seq(1:nrow(collapse_matrix))) {
226 new_contents[i] <- paste0(new_kable_dt[i, ], collapse = " & ")
Hao Zhu12b0ade2018-01-13 16:19:58 -0500227 table_info$contents[i + 1] <- new_contents[i]
Hao Zhu654c91f2017-07-03 14:03:34 -0400228 if (i != nrow(collapse_matrix)) {
Hao Zhu12b0ade2018-01-13 16:19:58 -0500229 row_midrule <- switch(
230 latex_hline,
231 "none" = "",
232 "full" = midline_groups(which(as.numeric(midrule_matrix[i, ]) > 0),
233 table_info$booktabs),
234 "major" = ifelse(
235 sum(as.numeric(midrule_matrix[i, ]) > 0) == ncol(midrule_matrix),
236 midline_groups(which(as.numeric(midrule_matrix[i, ]) > 0),
237 table_info$booktabs),
238 ""
georgeguieaeb0cd2018-03-30 17:39:46 -0500239 ),
240 "custom" = ifelse(
241 sum(as.numeric(midrule_matrix[i, custom_latex_hline])) > 0,
242 midline_groups(which(as.numeric(midrule_matrix[i, ]) > 0),
243 table_info$booktabs),
244 ""
245 )
Hao Zhu12b0ade2018-01-13 16:19:58 -0500246 )
Hao Zhu654c91f2017-07-03 14:03:34 -0400247 new_contents[i] <- paste0(new_contents[i], "\\\\\\\\\n", row_midrule)
248 }
Hao Zhub3f26ae2020-08-04 00:36:52 -0400249 out <- sub(contents[i + 1], new_contents[i], out, perl=TRUE)
Hao Zhuf4b35292017-06-25 22:38:37 -1000250 }
Hao Zhu8f202992017-07-15 02:20:18 -0400251 out <- gsub("\\\\addlinespace\n", "", out)
Hao Zhuf4b35292017-06-25 22:38:37 -1000252
253 out <- structure(out, format = "latex", class = "knitr_kable")
254 table_info$collapse_rows <- TRUE
Hao Zhuebdb3c22020-08-12 08:27:38 -0400255 table_info$collapse_matrix <- collapse_matrix
Hao Zhuf4b35292017-06-25 22:38:37 -1000256 attr(out, "kable_meta") <- table_info
georgeguieaeb0cd2018-03-30 17:39:46 -0500257 if(row_group_label_position == 'stack'){
258 group_row_index_list <- collapse_rows_index(kable_dt, head(columns, -1))
259 out <- collapse_rows_latex_stack(out, group_row_index_list, row_group_label_fonts)
260 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000261 return(out)
262}
263
Hao Zhuc9858942020-08-11 21:41:09 -0400264kable_dt_latex <- function(x, col_names) {
265 if (col_names) {
266 x <- x[-1]
267 }
268 data.frame(do.call(rbind, str_split(x, " & ")), stringsAsFactors = FALSE)
Hao Zhuf4b35292017-06-25 22:38:37 -1000269}
270
Hao Zhu5dd3e282018-05-20 18:39:48 -0400271collapse_new_dt_item <- function(x, span, width = NULL, align, valign) {
Hao Zhuf4b35292017-06-25 22:38:37 -1000272 if (span == 0) return("")
273 if (span == 1) return(x)
274 out <- paste0(
Hao Zhu5dd3e282018-05-20 18:39:48 -0400275 "\\\\multirow", valign, "\\{", -span, "\\}\\{",
Hao Zhuf4b35292017-06-25 22:38:37 -1000276 ifelse(is.null(width), "\\*", width),
277 "\\}\\{",
278 switch(align,
279 "l" = "\\\\raggedright\\\\arraybackslash ",
280 "c" = "\\\\centering\\\\arraybackslash ",
281 "r" = "\\\\raggedleft\\\\arraybackslash "),
282 x, "\\}"
283 )
284 return(out)
Hao Zhu2a87e8e2017-06-14 15:49:33 -0400285}
Hao Zhu654c91f2017-07-03 14:03:34 -0400286
287midline_groups <- function(x, booktabs = T) {
288 diffs <- c(1, diff(x))
289 start_indexes <- c(1, which(diffs > 1))
Hao Zhu12b0ade2018-01-13 16:19:58 -0500290 end_indexes <- c(start_indexes - 1, length(x))
Hao Zhu654c91f2017-07-03 14:03:34 -0400291 ranges <- paste0(x[start_indexes], "-", x[end_indexes])
292 if (booktabs) {
293 out <- paste0("\\\\cmidrule{", ranges, "}")
294 } else {
295 out <- paste0("\\\\cline{", ranges, "}")
296 }
297 out <- paste0(out, collapse = "\n")
298 return(out)
299}
georgeguieaeb0cd2018-03-30 17:39:46 -0500300
301
302collapse_rows_index <- function(kable_dt, columns) {
303 format_to_row_index <- function(x){
304 x = rle(x)
305 out = x$lengths
306 names(out) = x$values
307 out
308 }
309 group_rows_index_list <- lapply(columns, function(x) {
310 format_to_row_index(kable_dt[, x])
311 })
312 return(group_rows_index_list)
313}
314
315
316collapse_rows_latex_stack <- function(kable_input, group_row_index_list,
317 row_group_label_fonts){
318 merge_lists <- function(default_list, updated_list){
319 for(x in names(updated_list)){
320 default_list[[x]] <- updated_list[[x]]
321 }
322 return(default_list)
323 }
324 default_font_list <- list(
325 list(bold = T, italic = F),
326 list(bold = F, italic = T),
327 list(bold = F, italic = F)
328 )
329 n_default_fonts = length(default_font_list)
330 n_supplied_fonts = length(row_group_label_fonts)
331 group_row_font_list <- list()
332 out <- kable_input
333 for(i in 1:length(group_row_index_list)){
334 if(i > n_default_fonts){
335 group_row_args <- default_font_list[[n_default_fonts]]
336 } else {
337 group_row_args <- default_font_list[[i]]
338 }
339 if(i <= n_supplied_fonts){
340 group_row_args <- merge_lists(group_row_args, row_group_label_fonts[[i]])
341 }
342 group_row_args <- merge_lists(
343 list(kable_input = out, index = group_row_index_list[[i]]),
344 group_row_args)
345 out <- do.call(group_rows, group_row_args)
346 }
347 return(out)
348}