Debian Codegraph @

R/multi.R

raw
1 #' Format multiple vectors in a tabular display
2 #'
3 #' @description
4 #' `r lifecycle::badge("soft-deprecated")`
5 #'
6 #' The vectors are formatted to fit horizontally into a user-supplied number of
7 #' characters per row.
8 #'
9 #' The `colonnade()` function doesn't process the input but returns an object
10 #' with a [format()] and a [print()] method.
11 #' The implementations call [squeeze()] to create [pillar] objects and fit them to a given width.
12 #'
13 #' @param x A list, which can contain matrices or data frames.
14 #' If named, the names will be used as title for the pillars. Non-syntactic names
15 #' will be escaped.
16 #' @param has_row_id Include a column indicating row IDs? Pass `"*"` to mark
17 #' the row ID column with a star.
18 #' @param width Default width of the entire output, optional.
19 #' @inheritParams rlang::args_dots_empty
20 #' @keywords internal
21 #' @export
22 colonnade <- function(x, has_row_id = TRUE, width = NULL, ...) {
23 deprecate_stop("1.9.0", "pillar::colonnade()", "pillar::tbl_format_setup()")
24
25 if (!missing(...)) {
26 check_dots_empty(action = warn)
27 }
28
29 # Reset local cache for each new colonnade
30 num_colors(forget = TRUE)
31
32 x <- flatten_colonnade(x)
33 ret <- new_data_frame(x, has_row_id = has_row_id, class = "pillar_colonnade")
34 ret <- set_width(ret, width)
35 ret
36 }
37
38 flatten_colonnade <- function(x) {
39 out <- map2(
40 unname(x),
41 names2(x),
42 flatten_column
43 )
44
45 vec_rbind(
46 !!!out,
47 # .ptype = data_frame(names = list(), data = list())
48 .ptype = data_frame(names = character(), data = list())
49 )
50 }
51
52 flatten_column <- function(x, name) {
53 if (name != "") {
54 name <- tick_if_needed(name)
55 }
56
57 if (is.data.frame(x)) {
58 flatten_df_column(x, name)
59 } else if (is.matrix(x) && !inherits(x, c("Surv", "Surv2"))) {
60 flatten_matrix_column(x, name)
61 } else {
62 # Length-one list, will be unlist()ed afterwards
63 # data_frame(names = list(name), data = list(x))
64 data_frame(names = name, data = list(x))
65 }
66 }
67
68 flatten_df_column <- function(x, name) {
69 if (length(x) == 0) {
70 # data_frame(names = list(name), data = list(new_empty_col_sentinel(x)))
71 data_frame(names = name, data = list(new_empty_col_sentinel(x)))
72 } else {
73 x <- flatten_colonnade(unclass(x))
74 # x$names <- map(x$names, function(.x) c(name, .x))
75 x$names <- paste0("$", x$names)
76 x$names[[1]] <- paste0(name, x$names[[1]])
77 x
78 }
79 }
80
81 flatten_matrix_column <- function(x, name) {
82 if (ncol(x) == 0) {
83 data_frame(
84 # names = list(c(name, "[,0]")),
85 names = name,
86 data = list(new_empty_col_sentinel(x))
87 )
88 } else {
89 x_list <- map(seq_len(ncol(x)), function(i) x[, i])
90
91 idx <- colnames(x)
92 if (is.null(idx)) {
93 idx <- seq_along(x_list)
94 } else {
95 idx <- encodeString(idx, quote = '"')
96 }
97
98 # names <- map(idx, function(.x) c(name, .x))
99 names <- paste0("[,", idx, "]")
100 names[[1]] <- paste0(name, names[[1]])
101
102 data_frame(names = names, data = x_list)
103 }
104 }
105
106 new_empty_col_sentinel <- function(type) {
107 structure(list(type), class = c("pillar_empty_col"))
108 }
109
110 #' Squeeze a colonnade to a fixed width
111 #'
112 #' @description
113 #' `r lifecycle::badge("soft-deprecated")`
114 #'
115 #' The `squeeze()` function usually doesn't need to be called manually.
116 #' It returns an object suitable for printing and formatting at a fixed width
117 #' with additional information about omitted columns, which can be retrieved
118 #' via [extra_cols()].
119 #'
120 #' @keywords internal
121 #' @export
122 squeeze <- function(x, width = NULL, ...) {
123 deprecate_stop("1.5.0", "pillar::squeeze()")
124
125 squeeze_impl(x, width, ...)
126 }
127
128 squeeze_impl <- function(x, width = NULL, ...) {
129 # Shortcut for zero-height corner case
130 zero_height <- length(x$data) == 0L || length(x$data[[1]]) == 0L
131 if (zero_height) {
132 return(new_colonnade_squeezed(list(), colonnade = x, extra_cols = seq_along(x$data)))
133 }
134
135 if (is.null(width)) {
136 width <- get_width(x)
137 }
138
139 if (is.null(width)) {
140 width <- getOption("width")
141 }
142
143 rowid <- get_rowid_from_colonnade(x)
144 if (is.null(rowid)) {
145 rowid_width <- 0
146 } else {
147 rowid_width <- max(get_widths(rowid)) + 1L
148 }
149
150 col_widths <- colonnade_get_width(x, width, rowid_width)
151 col_widths_shown <- col_widths[!safe_is_na(col_widths$tier), ]
152 indexes <- split(seq_along(col_widths_shown$tier), col_widths_shown$tier)
153
154 out <- map(indexes, function(i) {
155 inner <- map2(col_widths_shown$pillar[i], col_widths_shown$width[i], pillar_format_parts)
156 if (!is.null(rowid)) {
157 inner <- c(list(pillar_format_parts(rowid, rowid_width - 1L)), inner)
158 }
159 inner
160 })
161
162 n_cols_shown <- nrow(col_widths_shown)
163 extra_cols <- seq2(n_cols_shown + 1L, length(x$data))
164 new_colonnade_squeezed(out, colonnade = x, extra_cols = extra_cols)
165 }
166
167 get_rowid_from_colonnade <- function(x) {
168 has_title <- any(x$names != "")
169
170 has_row_id <- attr(x, "has_row_id", exact = TRUE)
171 if (!is_false(has_row_id) && length(x$data) > 0) {
172 rowid <- rowidformat(
173 length(x$data[[1]]),
174 has_star = identical(has_row_id, "*"),
175 has_title_row = has_title
176 )
177 } else {
178 rowid <- NULL
179 }
180
181 rowid
182 }
183
184 new_colonnade_squeezed <- function(x, colonnade, extra_cols) {
185 formatted_tiers <- map(x, format_colonnade_tier)
186 formatted <- as_glue(as.character(unlist(formatted_tiers)))
187
188 structure(
189 list(formatted),
190 extra_cols = colonnade[extra_cols, ],
191 class = "pillar_squeezed_colonnade"
192 )
193 }
194
195 format_colonnade_tier <- function(x) {
196 "!!!!!DEBUG format_colonnade_tier(`v(x)`)"
197
198 if (length(x) == 0) {
199 return(character())
200 }
201
202 unlist(pmap(unname(x), paste))
203 }
204
205 #' @export
206 format.pillar_squeezed_colonnade <- function(x, ...) {
207 x[[1]]
208 }
209
210 #' @export
211 print.pillar_squeezed_colonnade <- function(x, ...) {
212 print(format(x, ...), ...)
213 invisible(x)
214 }
215
216 # Method registration happens in .onLoad()
217 knit_print.pillar_squeezed_colonnade <- function(x, ...) {
218 unlist(map(x, knit_print_squeezed_colonnade_tier))
219 }
220
221 knit_print_squeezed_colonnade_tier <- function(x) {
222 # Hack
223 header <- map_chr(map(x, `[[`, "capital_format"), `[[`, "title_format")
224 col <- map(x, function(xx) c(xx[["capital_format"]][["type_format"]], xx[["shaft_format"]]))
225
226 knitr::kable(as.data.frame(col), row.names = NA, col.names = header)
227 }
228
229 #' Retrieve information about columns that didn't fit the available width
230 #'
231 #' @description
232 #' `r lifecycle::badge("soft-deprecated")`
233 #'
234 #' Formatting a [colonnade] object may lead to some columns being omitted
235 #' due to width restrictions. This method returns a character vector that
236 #' describes each of the omitted columns.
237 #'
238 #' @param x The result of [squeeze()] on a [colonnade] object
239 #' @inheritParams rlang::args_dots_used
240 #' @keywords internal
241 #' @export
242 extra_cols <- function(x, ...) {
243 deprecate_stop("1.5.0", "pillar::extra_cols()")
244
245 if (!missing(...)) {
246 check_dots_used(action = warn)
247 }
248
249 UseMethod("extra_cols")
250 }
251
252 #' @rdname extra_cols
253 #' @param n The number of extra columns to return; the returned vector will
254 #' always contain as many elements as there are extra columns, but elements
255 #' beyond `n` will be `NA`.
256 #' @export
257 extra_cols.pillar_squeezed_colonnade <- function(x, ..., n = Inf) {
258 extra_cols_impl(x, n)
259 }
260
261 extra_cols_impl <- function(x, n = NULL) {
262 extra_cols <- attr(x, "extra_cols", exact = TRUE)
263 ret <- rep(NA_character_, length(extra_cols$data))
264
265 if (is.null(n)) {
266 n <- Inf
267 }
268
269 idx <- seq_len(min(length(extra_cols$data), n))
270 ret[idx] <- map2_chr(extra_cols$data[idx], extra_cols$names[idx], format_abbrev, space = NBSP)
271 ret
272 }
273
274 #' @export
275 format.pillar_colonnade <- function(x, ...) {
276 format(squeeze_impl(x, ...))
277 }
278
279 #' @export
280 print.pillar_colonnade <- function(x, ...) {
281 print(format(x, ...))
282 }
283
284 #' @rdname colonnade
285 #' @usage NULL
286 #' @aliases NULL
287 colonnade_get_width <- function(x, width, rowid_width) {
288 #' @details
289 #' Pillars may be distributed over multiple tiers if
290 #' `width > getOption("width")`. In this case each tier is at most
291 #' `getOption("width")` characters wide. The very first step of formatting
292 #' is to determine how many tiers are shown at most, and the width of each
293 #' tier.
294 tier_widths <- get_tier_widths(width, length(x$data), rowid_width)
295
296 #'
297 #' To avoid unnecessary computation for showing very wide colonnades, a first
298 #' pass tries to fit all capitals into the tiers.
299 init_cols <- min(length(x$data), sum(floor((tier_widths + 1L) / (MIN_PILLAR_WIDTH + 1L))))
300 capitals <- map2(x$data[seq_len(init_cols)], x$names[seq_len(init_cols)], pillar_capital)
301 init_col_widths_df <- colonnade_compute_tiered_col_widths(capitals, tier_widths)
302 pillar_shown <- init_col_widths_df$id[!safe_is_na(init_col_widths_df$tier)]
303 if (length(pillar_shown) < init_cols) {
304 # (Include one more pillar to indicate that the data is too wide.)
305 pillar_shown <- c(pillar_shown, pillar_shown[length(pillar_shown)] + 1L)
306 }
307
308 #' For each pillar whose capital fits, it is then decided in which tier it is
309 #' shown, if at all, and how much horizontal space it may use (either its
310 #' minimum or its maximum width).
311 shafts <- map(x$data[pillar_shown], pillar_shaft)
312 pillars <- map2(capitals[pillar_shown], shafts, new_pillar_1e)
313 col_widths_df <- colonnade_compute_tiered_col_widths(pillars, tier_widths)
314
315 #' Remaining space is then distributed proportionally to pillars that do not
316 #' use their desired width.
317 colonnade_distribute_space_df(col_widths_df, tier_widths)
318 }
319
320 get_tier_widths <- function(width, ncol, rowid_width, tier_width = getOption("width")) {
321 if (!is.finite(width)) {
322 pos <- seq(0, length.out = ncol + 1L, by = tier_width)
323 } else if (width < tier_width) {
324 pos <- c(0L, width)
325 } else {
326 pos <- seq(0, width + tier_width - 1, by = tier_width)
327 }
328
329 widths <- diff(pos) - rowid_width
330 widths[widths >= 1L]
331 }
332
333 colonnade_compute_tiered_col_widths <- function(pillars, tier_widths) {
334 max_tier_width <- max(tier_widths)
335
336 max_widths <- pmin(map_int(map(pillars, get_widths), max), max_tier_width)
337 min_widths <- pmin(map_int(map(pillars, get_min_widths), max), max_widths)
338
339 ret <- colonnade_compute_tiered_col_widths_df(max_widths, min_widths, tier_widths)
340 ret$pillar <- pillars
341 ret
342 }
343
344 #' @rdname colonnade
345 #' @usage NULL
346 #' @aliases NULL
347 colonnade_compute_tiered_col_widths_df <- function(max_widths, min_widths, tier_widths) {
348 "!!!!!DEBUG colonnade_compute_tiered_col_widths_df(`v(tier_widths)`)"
349
350 max_tier_width <- max(tier_widths)
351
352 # Safety:
353 max_widths <- pmin(max_widths, max_tier_width)
354 min_widths <- pmin(min_widths, max_tier_width)
355
356 id <- seq_along(max_widths)
357 col_df <- data.frame(id, max_widths, min_widths, row.names = NULL)
358
359 #' @details
360 #' For fitting pillars in one or more tiers, first a check is made
361 #' if all pillars fit with their maximum width (e.g.,
362 #' `option(tibble.width = Inf)` or narrow colonnade).
363 max_fit <- distribute_pillars(col_df$max_widths, tier_widths)
364 #' If yes, this is the resulting fit, no more work needs to be done.
365 if (all_pillars_fit(max_fit)) {
366 return(max_fit)
367 }
368
369 #' Otherwise, if the maximum width is too wide, the same test
370 #' is carried out with the minimum width.
371 #' If this is still too wide, this is the resulting fit.
372 min_fit <- distribute_pillars(col_df$min_widths, tier_widths)
373 if (!all_pillars_fit(min_fit)) {
374 return(min_fit)
375 }
376
377 #' Otherwise, some tiers from the start
378 #' will contain pillars with their maximum width,
379 #' one tier will contain some pillars with maximum and some with minimum width,
380 #' and the remaining tiers contain pillars with their minimum width only.
381 #'
382 #' For this, we compute a "reverse minimum assignment".
383 min_fit_rev <- distribute_pillars_rev(col_df$min_widths, tier_widths)
384
385 combined_fit <- combine_pillar_distributions(max_fit, min_fit_rev, tier_widths)
386
387 combined_fit$max_widths <- col_df$max_widths
388 combined_fit
389 }
390
391 #' @rdname colonnade
392 #' @usage NULL
393 #' @aliases NULL
394 combine_pillar_distributions <- function(max_fit, min_fit_rev, tier_widths) {
395 #' @details
396 #' We determine the cut point where minimum and maximum assignment
397 #' agree.
398 #' The following strategy is applied:
399 #'
400 #' 1. First, we determine the tier in which the cut point lies.
401 #' This is the first instance of a column that ends up in the same tier
402 #' for both minimum and maximum assignment.
403 cut_point_tier <- max_fit$tier[min(which(max_fit$tier == min_fit_rev$tier))]
404 #' 2. A set of candidate cut points is derived.
405 cut_point_candidates <- which(max_fit$tier == cut_point_tier)
406 #' 3. We consult the column offsets. The last column where the minimum assignment
407 #' has a greater or equal offset than the maximum assignment is our latest
408 #' cut point.
409 cut_point_candidate_idx <- which(max_fit$offset_after[cut_point_candidates] <= min_fit_rev$offset_after[cut_point_candidates])
410 if (length(cut_point_candidate_idx) > 0) {
411 cut_point <- cut_point_candidates[max(cut_point_candidate_idx)]
412 } else {
413 #' If no such column exists, the cut point is the column just before our
414 #' first candidate.
415 cut_point <- cut_point_candidates[[1]] - 1L
416 }
417
418 #' 4. Finally, we combine maximum and minimum reverse fits at the cut point.
419 #' We don't need to redistribute anything here.
420 max_fit_cut <- max_fit[seq_len(cut_point), ]
421 min_fit_cut <- min_fit_rev[seq2(cut_point + 1L, nrow(min_fit_rev)), ]
422 rbind(max_fit_cut, min_fit_cut)
423 }
424
425 #' @rdname colonnade
426 #' @usage NULL
427 #' @aliases NULL
428 distribute_pillars <- function(widths, tier_widths) {
429 tier <- rep(NA_integer_, length(widths))
430 offset_after <- rep(NA_integer_, length(widths))
431 current_tier <- 1L
432 current_x <- 0L
433
434 #' @details
435 #' Fitting pillars into tiers is very similar to a word-wrapping algorithm.
436 for (i in seq_along(widths)) {
437 current_width <- widths[[i]]
438 #' In a loop, new tiers are opened if the current tier overflows.
439 if (current_x + current_width > tier_widths[[current_tier]]) {
440 #' If a column is too wide to fit a single tier, it will never be
441 #' displayed, and the colonnade will be truncated there.
442 #' This case should never occur with reasonable display widths larger than
443 #' 30 characters.
444 if (current_width > tier_widths[[current_tier]]) {
445 if (current_tier == length(tier_widths) || current_width > tier_widths[[current_tier + 1]]) {
446 break
447 }
448 }
449
450 current_tier <- current_tier + 1L
451 current_x <- 0L
452 #' Truncation also happens if all available tiers are filled.
453 if (current_tier > length(tier_widths)) break
454 }
455
456 tier[[i]] <- current_tier
457 current_x <- current_x + current_width
458 offset_after[[i]] <- current_x
459 current_x <- current_x + 1L
460 }
461
462 data_frame(id = seq_along(widths), tier = tier, width = widths, offset_after = offset_after)
463 }
464
465 distribute_pillars_rev <- function(widths, tier_widths) {
466 ret <- distribute_pillars(rev(widths), rev(tier_widths))
467 ret[2:4] <- ret[rev(seq_along(widths)), 2:4]
468 tier <- length(tier_widths) + 1L - ret$tier
469 ret$tier <- tier
470
471 splits <- split(seq_along(tier), tier)
472 tier_widths <- tier_widths[stats::na.omit(unique(tier))]
473
474 new_offset_after <- unlist(map2(unname(splits), tier_widths, function(.x, .y) {
475 new_offset_after <- cumsum(ret$width[.x] + 1)
476 new_offset_after - max(new_offset_after) + .y
477 }))
478
479 ret$offset_after <- c(new_offset_after, rep(NA_integer_, sum(is.na(tier))))
480
481 ret
482 }
483
484 all_pillars_fit <- function(tier_df) {
485 rows <- nrow(tier_df)
486 rows == 0 || !safe_any_na(tier_df$tier[[nrow(tier_df)]])
487 }
488
489 #' @rdname colonnade
490 #' @usage NULL
491 #' @aliases NULL
492 colonnade_distribute_space_df <- function(col_widths_df, tier_widths) {
493 "!!!!!DEBUG colonnade_distribute_space_df(`v(tier_widths)`)"
494
495 col_widths_split <- split(col_widths_df, col_widths_df$tier)
496 tier_widths <- tier_widths[seq_along(col_widths_split)]
497 col_widths_apply <- map2(col_widths_split, tier_widths, function(x, width) {
498 x$width <- x$width + colonnade_distribute_space(x$width, x$max_widths, width)
499 x
500 })
501
502 bind_rows(unname(col_widths_apply))
503 }
504
505 #' @rdname colonnade
506 #' @usage NULL
507 #' @aliases NULL
508 colonnade_distribute_space <- function(col_widths, max_widths, width) {
509 if (any(is.na(col_widths))) {
510 return(col_widths)
511 }
512
513 missing_space <- max_widths - col_widths
514 # Shortcut to avoid division by zero
515 if (all(missing_space == 0L)) {
516 return(rep_along(col_widths, 0L))
517 }
518
519 #' @details
520 #' The remaining space is distributed from left to right.
521 #' Each column gains space proportional to the fraction of missing and
522 #' remaining space,
523 occupied_width <- sum(col_widths + 1L) - 1L
524 remaining_width <- max(min(width - occupied_width, sum(missing_space)), 0L)
525 added_space_prop <- missing_space / sum(missing_space) * remaining_width
526
527 #' rounded down.
528 added_space_ceil <- ceiling(added_space_prop)
529 added_space_floor <- floor(added_space_prop)
530 added_space_diff <- added_space_ceil - added_space_floor
531 added_space <- ifelse(
532 #' Any space remaining after rounding is distributed from left to right,
533 #' one space per column.
534 sum(added_space_floor) + cumsum(added_space_diff) <= remaining_width,
535 added_space_ceil,
536 added_space_floor
537 )
538
539 added_space
540 }