blob: 4ae014502d2287931cd51bcad8d9ead87e35318e [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
Jakob Richteraebd8292018-10-31 16:27:29 +010010#' @param columns A numeric value or vector indicating in which column(s) rows
11#' 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 Zhu8a160b12017-06-26 13:41:35 -100026#'
Hao Zhu5a7689e2017-06-26 15:37:24 -100027#' @examples dt <- data.frame(a = c(1, 1, 2, 2), b = c("a", "a", "a", "b"))
28#' x <- knitr::kable(dt, "html")
29#' collapse_rows(x)
30#'
Hao Zhuf4b35292017-06-25 22:38:37 -100031#' @export
Hao Zhu12b0ade2018-01-13 16:19:58 -050032collapse_rows <- function(kable_input, columns = NULL,
Hao Zhuec169362018-05-21 01:05:29 -040033 valign = c("middle", "top", "bottom"),
georgeguieaeb0cd2018-03-30 17:39:46 -050034 latex_hline = c("full", "major", "none", "custom"),
35 row_group_label_position = c('identity', 'stack'),
36 custom_latex_hline = NULL,
37 row_group_label_fonts = NULL,
38 headers_to_remove = NULL) {
Hao Zhu2a87e8e2017-06-14 15:49:33 -040039 kable_format <- attr(kable_input, "format")
40 if (!kable_format %in% c("html", "latex")) {
Hao Zhu401ebd82018-01-14 17:10:20 -050041 warning("Please specify format in kable. kableExtra can customize either ",
42 "HTML or LaTeX outputs. See https://haozhu233.github.io/kableExtra/ ",
43 "for details.")
Hao Zhu2a87e8e2017-06-14 15:49:33 -040044 return(kable_input)
45 }
Hao Zhuec169362018-05-21 01:05:29 -040046 valign <- match.arg(valign, c("middle", "top", "bottom"))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040047 if (kable_format == "html") {
Hao Zhu5dd3e282018-05-20 18:39:48 -040048 return(collapse_rows_html(kable_input, columns, valign))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040049 }
50 if (kable_format == "latex") {
georgeguieaeb0cd2018-03-30 17:39:46 -050051 latex_hline <- match.arg(latex_hline, c("full", "major", "none", "custom"))
52 row_group_label_position <- match.arg(row_group_label_position,
53 c('identity', 'stack'))
Hao Zhu5dd3e282018-05-20 18:39:48 -040054 return(collapse_rows_latex(kable_input, columns, latex_hline, valign,
georgeguieaeb0cd2018-03-30 17:39:46 -050055 row_group_label_position, row_group_label_fonts, custom_latex_hline,
56 headers_to_remove))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040057 }
58}
59
Hao Zhu5dd3e282018-05-20 18:39:48 -040060collapse_rows_html <- function(kable_input, columns, valign) {
Hao Zhu2a87e8e2017-06-14 15:49:33 -040061 kable_attrs <- attributes(kable_input)
Hao Zhu558c72f2017-07-24 15:12:00 -040062 kable_xml <- read_kable_as_xml(kable_input)
Hao Zhu2a87e8e2017-06-14 15:49:33 -040063 kable_tbody <- xml_tpart(kable_xml, "tbody")
64
65 kable_dt <- rvest::html_table(xml2::read_html(as.character(kable_input)))[[1]]
Hao Zhuf4b35292017-06-25 22:38:37 -100066 if (is.null(columns)) {
67 columns <- seq(1, ncol(kable_dt))
68 }
Hao Zhu23456762018-03-26 12:30:10 -040069 if (!is.null(kable_attrs$header_above)) {
70 kable_dt_col_names <- unlist(kable_dt[kable_attrs$header_above, ])
71 kable_dt <- kable_dt[-(1:kable_attrs$header_above),]
72 names(kable_dt) <- kable_dt_col_names
73 }
74 kable_dt$row_id <- seq(nrow(kable_dt))
Hao Zhu2a87e8e2017-06-14 15:49:33 -040075 collapse_matrix <- collapse_row_matrix(kable_dt, columns)
76
77 for (i in 1:nrow(collapse_matrix)) {
78 matrix_row <- collapse_matrix[i, ]
Hao Zhu38cdcdb2017-06-27 09:08:30 -100079 names(matrix_row) <- names(collapse_matrix)
Hao Zhu3166f062017-06-26 07:51:46 -100080 target_row <- xml_child(kable_tbody, i)
81 row_node_rm_count <- 0
82 for (j in 1:length(matrix_row)) {
83 collapsing_col <- as.numeric(sub("x", "", names(matrix_row)[j])) -
84 row_node_rm_count
85 target_cell <- xml_child(target_row, collapsing_col)
86 if (matrix_row[j] == 0) {
87 xml_remove(target_cell)
88 row_node_rm_count <- row_node_rm_count + 1
89 } else if (matrix_row[j] != 1) {
90 xml_attr(target_cell, "rowspan") <- matrix_row[j]
91 xml_attr(target_cell, "style") <- paste0(
92 xml_attr(target_cell, "style"),
Hao Zhu5dd3e282018-05-20 18:39:48 -040093 "vertical-align: ", valign, " !important;")
Hao Zhu2a87e8e2017-06-14 15:49:33 -040094 }
95 }
96 }
97
Hao Zhuf2dfd142017-07-24 14:43:28 -040098 out <- as_kable_xml(kable_xml)
Hao Zhu2a87e8e2017-06-14 15:49:33 -040099 attributes(out) <- kable_attrs
Hao Zhuf2100832018-01-11 16:20:29 -0500100 if (!"kableExtra" %in% class(out)) class(out) <- c("kableExtra", class(out))
Hao Zhu2a87e8e2017-06-14 15:49:33 -0400101 return(out)
102}
103
Hao Zhuf4b35292017-06-25 22:38:37 -1000104collapse_row_matrix <- function(kable_dt, columns, html = T) {
105 if (html) {
106 column_block <- function(x) c(x, rep(0, x - 1))
107 } else {
108 column_block <- function(x) c(rep(0, x - 1), x)
109 }
110 mapping_matrix <- list()
111 for (i in columns) {
112 mapping_matrix[[paste0("x", i)]] <- unlist(lapply(
Tomasz Kalinowski6b4b6f12018-09-18 16:55:19 -0400113 rle(kable_dt[, i])$lengths, column_block))
Hao Zhuf4b35292017-06-25 22:38:37 -1000114 }
115 mapping_matrix <- data.frame(mapping_matrix)
116 return(mapping_matrix)
117}
118
Hao Zhu5dd3e282018-05-20 18:39:48 -0400119collapse_rows_latex <- function(kable_input, columns, latex_hline, valign,
georgeguieaeb0cd2018-03-30 17:39:46 -0500120 row_group_label_position, row_group_label_fonts,
121 custom_latex_hline, headers_to_remove) {
Hao Zhuf4b35292017-06-25 22:38:37 -1000122 table_info <- magic_mirror(kable_input)
Hao Zhu3fc0e882018-04-03 16:06:41 -0400123 out <- solve_enc(kable_input)
Hao Zhu064990d2017-10-17 18:08:42 -0400124
Hao Zhu5dd3e282018-05-20 18:39:48 -0400125 valign <- switch(
126 valign,
127 top = "\\[t\\]",
128 middle = "",
129 bottom = "\\[b\\]"
130 )
131
Hao Zhuf4b35292017-06-25 22:38:37 -1000132 if (is.null(columns)) {
133 columns <- seq(1, table_info$ncol)
134 }
Hao Zhu064990d2017-10-17 18:08:42 -0400135
Hao Zhuf4b35292017-06-25 22:38:37 -1000136 contents <- table_info$contents
137 kable_dt <- kable_dt_latex(contents)
georgeguieaeb0cd2018-03-30 17:39:46 -0500138
139 collapse_matrix_rev <- collapse_row_matrix(kable_dt, columns, html = TRUE)
Hao Zhu01b15b82018-01-12 17:48:21 -0500140 collapse_matrix <- collapse_row_matrix(kable_dt, columns, html = FALSE)
Hao Zhuf4b35292017-06-25 22:38:37 -1000141
142 new_kable_dt <- kable_dt
Jakob Richteraebd8292018-10-31 16:27:29 +0100143 for (j in seq_along(columns)) {
Hao Zhuf4b35292017-06-25 22:38:37 -1000144 column_align <- table_info$align_vector_origin[columns[j]]
145 column_width <- ifelse(
146 is.null(table_info$column_width[[paste0("column_", columns[j])]]),
147 "*", table_info$column_width[paste0("column_", columns[j])])
148 for (i in seq(1:nrow(collapse_matrix))) {
georgeguieaeb0cd2018-03-30 17:39:46 -0500149 if(row_group_label_position == 'stack'){
Jakob Richteraebd8292018-10-31 16:27:29 +0100150 if(columns[j] < ncol(collapse_matrix) || collapse_matrix_rev[i, j] == 0){
151 new_kable_dt[i, columns[j]] <- ''
georgeguieaeb0cd2018-03-30 17:39:46 -0500152 }
153 } else {
Jakob Richteraebd8292018-10-31 16:27:29 +0100154 new_kable_dt[i, columns[j]] <- collapse_new_dt_item(
155 kable_dt[i, columns[j]], collapse_matrix[i, j], column_width,
Hao Zhu5dd3e282018-05-20 18:39:48 -0400156 align = column_align, valign = valign
georgeguieaeb0cd2018-03-30 17:39:46 -0500157 )
158 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000159 }
160 }
Hao Zhu654c91f2017-07-03 14:03:34 -0400161
162 midrule_matrix <- collapse_row_matrix(kable_dt, seq(1, table_info$ncol),
163 html = F)
164 midrule_matrix[setdiff(seq(1, table_info$ncol), columns)] <- 1
165
166 ex_bottom <- length(contents) - 1
167 contents[2:ex_bottom] <- paste0(contents[2:ex_bottom], "\\\\\\\\")
168 if (!table_info$booktabs) {
169 contents[2:ex_bottom] <- paste0(contents[2:ex_bottom], "\n\\\\hline")
170 }
Hao Zhu01b15b82018-01-12 17:48:21 -0500171
172 new_contents <- c()
georgeguieaeb0cd2018-03-30 17:39:46 -0500173 if(row_group_label_position == 'stack'){
174 if(is.null(headers_to_remove)) headers_to_remove <- head(columns, -1)
175 table_info$colnames[headers_to_remove] <- ''
176 new_header <- paste(table_info$colnames, collapse = ' & ')
177 out <- sub(contents[1], new_header, out)
178 table_info$contents[1] <- new_header
179 }
180 if(latex_hline == 'custom' & is.null(custom_latex_hline)){
181 if(row_group_label_position == 'stack'){
182 custom_latex_hline = 1:2
183 } else {
184 custom_latex_hline = 1
185 }
186 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000187 for (i in seq(1:nrow(collapse_matrix))) {
188 new_contents[i] <- paste0(new_kable_dt[i, ], collapse = " & ")
Hao Zhu12b0ade2018-01-13 16:19:58 -0500189 table_info$contents[i + 1] <- new_contents[i]
Hao Zhu654c91f2017-07-03 14:03:34 -0400190 if (i != nrow(collapse_matrix)) {
Hao Zhu12b0ade2018-01-13 16:19:58 -0500191 row_midrule <- switch(
192 latex_hline,
193 "none" = "",
194 "full" = midline_groups(which(as.numeric(midrule_matrix[i, ]) > 0),
195 table_info$booktabs),
196 "major" = ifelse(
197 sum(as.numeric(midrule_matrix[i, ]) > 0) == ncol(midrule_matrix),
198 midline_groups(which(as.numeric(midrule_matrix[i, ]) > 0),
199 table_info$booktabs),
200 ""
georgeguieaeb0cd2018-03-30 17:39:46 -0500201 ),
202 "custom" = ifelse(
203 sum(as.numeric(midrule_matrix[i, custom_latex_hline])) > 0,
204 midline_groups(which(as.numeric(midrule_matrix[i, ]) > 0),
205 table_info$booktabs),
206 ""
207 )
Hao Zhu12b0ade2018-01-13 16:19:58 -0500208 )
Hao Zhu654c91f2017-07-03 14:03:34 -0400209 new_contents[i] <- paste0(new_contents[i], "\\\\\\\\\n", row_midrule)
210 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000211 out <- sub(contents[i + 1], new_contents[i], out)
212 }
Hao Zhu8f202992017-07-15 02:20:18 -0400213 out <- gsub("\\\\addlinespace\n", "", out)
Hao Zhuf4b35292017-06-25 22:38:37 -1000214
215 out <- structure(out, format = "latex", class = "knitr_kable")
216 table_info$collapse_rows <- TRUE
217 attr(out, "kable_meta") <- table_info
georgeguieaeb0cd2018-03-30 17:39:46 -0500218 if(row_group_label_position == 'stack'){
219 group_row_index_list <- collapse_rows_index(kable_dt, head(columns, -1))
220 out <- collapse_rows_latex_stack(out, group_row_index_list, row_group_label_fonts)
221 }
Hao Zhuf4b35292017-06-25 22:38:37 -1000222 return(out)
223}
224
225kable_dt_latex <- function(x) {
226 data.frame(do.call(rbind, str_split(x[-1], " & ")), stringsAsFactors = FALSE)
227}
228
Hao Zhu5dd3e282018-05-20 18:39:48 -0400229collapse_new_dt_item <- function(x, span, width = NULL, align, valign) {
Hao Zhuf4b35292017-06-25 22:38:37 -1000230 if (span == 0) return("")
231 if (span == 1) return(x)
232 out <- paste0(
Hao Zhu5dd3e282018-05-20 18:39:48 -0400233 "\\\\multirow", valign, "\\{", -span, "\\}\\{",
Hao Zhuf4b35292017-06-25 22:38:37 -1000234 ifelse(is.null(width), "\\*", width),
235 "\\}\\{",
236 switch(align,
237 "l" = "\\\\raggedright\\\\arraybackslash ",
238 "c" = "\\\\centering\\\\arraybackslash ",
239 "r" = "\\\\raggedleft\\\\arraybackslash "),
240 x, "\\}"
241 )
242 return(out)
Hao Zhu2a87e8e2017-06-14 15:49:33 -0400243}
Hao Zhu654c91f2017-07-03 14:03:34 -0400244
245midline_groups <- function(x, booktabs = T) {
246 diffs <- c(1, diff(x))
247 start_indexes <- c(1, which(diffs > 1))
Hao Zhu12b0ade2018-01-13 16:19:58 -0500248 end_indexes <- c(start_indexes - 1, length(x))
Hao Zhu654c91f2017-07-03 14:03:34 -0400249 ranges <- paste0(x[start_indexes], "-", x[end_indexes])
250 if (booktabs) {
251 out <- paste0("\\\\cmidrule{", ranges, "}")
252 } else {
253 out <- paste0("\\\\cline{", ranges, "}")
254 }
255 out <- paste0(out, collapse = "\n")
256 return(out)
257}
georgeguieaeb0cd2018-03-30 17:39:46 -0500258
259
260collapse_rows_index <- function(kable_dt, columns) {
261 format_to_row_index <- function(x){
262 x = rle(x)
263 out = x$lengths
264 names(out) = x$values
265 out
266 }
267 group_rows_index_list <- lapply(columns, function(x) {
268 format_to_row_index(kable_dt[, x])
269 })
270 return(group_rows_index_list)
271}
272
273
274collapse_rows_latex_stack <- function(kable_input, group_row_index_list,
275 row_group_label_fonts){
276 merge_lists <- function(default_list, updated_list){
277 for(x in names(updated_list)){
278 default_list[[x]] <- updated_list[[x]]
279 }
280 return(default_list)
281 }
282 default_font_list <- list(
283 list(bold = T, italic = F),
284 list(bold = F, italic = T),
285 list(bold = F, italic = F)
286 )
287 n_default_fonts = length(default_font_list)
288 n_supplied_fonts = length(row_group_label_fonts)
289 group_row_font_list <- list()
290 out <- kable_input
291 for(i in 1:length(group_row_index_list)){
292 if(i > n_default_fonts){
293 group_row_args <- default_font_list[[n_default_fonts]]
294 } else {
295 group_row_args <- default_font_list[[i]]
296 }
297 if(i <= n_supplied_fonts){
298 group_row_args <- merge_lists(group_row_args, row_group_label_fonts[[i]])
299 }
300 group_row_args <- merge_lists(
301 list(kable_input = out, index = group_row_index_list[[i]]),
302 group_row_args)
303 out <- do.call(group_rows, group_row_args)
304 }
305 return(out)
306}