1 |
## #' Page Dimensions |
|
2 |
## #' |
|
3 |
## #' Dimensions for mapping page dimensions to text dimensions |
|
4 |
## #' @references https://www.ietf.org/rfc/rfc0678.txt |
|
5 |
## #' @export |
|
6 |
## #' @rdname pagedims |
|
7 |
## lpi_vert <- 6 |
|
8 |
## #' @export |
|
9 |
## #' @rdname pagedims |
|
10 |
## cpi_horiz <- 10 |
|
11 |
## #' @export |
|
12 |
## #' @rdname pagedims |
|
13 |
## horiz_margin_chars <- 13 |
|
14 |
## #' @export |
|
15 |
## #' @rdname pagedims |
|
16 |
## horiz_margin_inches <- horiz_margin_chars / cpi_horiz |
|
17 |
## #' @export |
|
18 |
## #' @rdname pagedims |
|
19 |
## vert_margin_lines <- 6 |
|
20 |
## #' @export |
|
21 |
## #' @rdname pagedims |
|
22 |
## vert_margin_inches <- vert_margin_lines / lpi_vert |
|
23 | ||
24 |
## #' Physical Page dimensions to chars x lines |
|
25 |
## #' |
|
26 |
## #' Calculate number of lines long and characters wide a page size is, |
|
27 |
## #' after excluding margins |
|
28 |
## #' @export |
|
29 |
## #' @examples |
|
30 |
## #' phys_page_to_lc() |
|
31 |
## phys_page_to_lc <- function(width = 8.5, len = 11, |
|
32 |
## h_margin = horiz_margin_inches, |
|
33 |
## v_margin = vert_margin_inches) { |
|
34 |
## lgl_width <- width - h_margin |
|
35 |
## lgl_len <- len - v_margin |
|
36 |
## c(chars_wide = floor(lgl_width * cpi_horiz), |
|
37 |
## lines_long = floor(lgl_len * lpi_vert)) |
|
38 |
## } |
|
39 | ||
40 |
#' @name pagination_algo |
|
41 |
#' @rdname pagination_algo |
|
42 |
#' @title Pagination |
|
43 |
#' @section Pagination Algorithm: |
|
44 |
#' |
|
45 |
#' Pagination is performed independently in the vertical and horizontal |
|
46 |
#' directions based solely on a *pagination data.frame*, which includes the |
|
47 |
#' following information for each row/column: |
|
48 |
#' |
|
49 |
#' - number of lines/characters rendering the row will take **after |
|
50 |
#' word-wrapping** (`self_extent`) |
|
51 |
#' - the indices (`reprint_inds`) and number of lines (`par_extent`) |
|
52 |
#' of the rows which act as **context** for the row |
|
53 |
#' - the row's number of siblings and position within its siblings |
|
54 |
#' |
|
55 |
#' Given `lpp` (`cpp`) already adjusted for rendered elements which |
|
56 |
#' are not rows/columns and a dataframe of pagination information, |
|
57 |
#' pagination is performed via the following algorithm, and with a |
|
58 |
#' `start = 1`: |
|
59 |
#' |
|
60 |
#' Core Pagination Algorithm: |
|
61 |
#' 1. Initial guess for pagination point is `start + lpp` (`start + cpp`) |
|
62 |
#' |
|
63 |
#' 2. While the guess is not a valid pagination position, and `guess > |
|
64 |
#' start`, decrement guess and repeat |
|
65 |
#' - an error is thrown if all possible pagination positions between |
|
66 |
#' `start` and `start + lpp` (`start + cpp`) would ever be `< start` |
|
67 |
#' after decrementing |
|
68 |
#' 3. Retain pagination index |
|
69 |
#' 4. if pagination point was less than `NROW(tt)` (`ncol(tt)`), set |
|
70 |
#' `start` to `pos + 1`, and repeat steps (1) - (4). |
|
71 |
#' |
|
72 |
#' Validating pagination position: |
|
73 |
#' |
|
74 |
#' Given an (already adjusted) `lpp` or `cpp` value, a pagination is invalid if: |
|
75 |
#' |
|
76 |
#' - The rows/columns on the page would take more than (adjusted) `lpp` lines/`cpp` |
|
77 |
#' characters to render **including** |
|
78 |
#' - word-wrapping |
|
79 |
#' - (vertical only) context repetition |
|
80 |
#' - (vertical only) footnote messages and or section divider lines |
|
81 |
#' take up too many lines after rendering rows |
|
82 |
#' - (vertical only) row is a label or content (row-group summary) row |
|
83 |
#' - (vertical only) row at the pagination point has siblings, and |
|
84 |
#' it has less than `min_siblings` preceding or following siblings |
|
85 |
#' - pagination would occur within a sub-table listed in `nosplitin` |
|
86 |
#' |
|
87 |
NULL |
|
88 | ||
89 |
#' Create row of pagination data frame |
|
90 |
#' @param nm character(1). Name |
|
91 |
#' @param lab character(1). Label |
|
92 |
#' @param rnum numeric(1). Absolute row number |
|
93 |
#' @param pth character or NULL. Path within larger table |
|
94 |
#' @param sibpos integer(1). Position among sibling rows |
|
95 |
#' @param nsibs integer(1). Number of siblings (including self). |
|
96 |
#' @param extent numeric(1). Number of lines required to print the row |
|
97 |
#' @param colwidths numeric. Column widths |
|
98 |
#' @param repext integer(1). Number of lines required to reprint all context for this row if it appears directly |
|
99 |
#' after pagination. |
|
100 |
#' @param repind integer. Vector of row numbers to be reprinted if this row appears directly after pagination. |
|
101 |
#' @param indent integer. Indent |
|
102 |
#' @param rclass character(1). Class of row object. |
|
103 |
#' @param nrowrefs integer(1). Number of row referential footnotes for this row |
|
104 |
#' @param ncellrefs integer(1). Number of cell referential footnotes for the cells in this row |
|
105 |
#' @param nreflines integer(1). Total number of lines required by all referential footnotes |
|
106 |
#' @param force_page logical(1). Currently Ignored. |
|
107 |
#' @param page_title logical(1). Currently Ignored. |
|
108 |
#' @param trailing_sep character(1). The string to used as a separator below this row during printing (or |
|
109 |
#' `NA_character_` for no separator). |
|
110 |
#' @param row ANY. Object representing the row, which is used for default values of \code{nm}, \code{lab}, |
|
111 |
#' \code{extent} and \code{rclass} if provided. Must have methods for \code{obj_name}, \code{obj_label}, |
|
112 |
#' and \code{nlines}, respectively, for default values of \code{nm}, \code{lab} and \code{extent} to |
|
113 |
#' be retrieved, respectively. |
|
114 |
#' |
|
115 |
#' @return a single row data.frame with the columns appropriate for a pagination info data frame. |
|
116 |
#' @export |
|
117 |
pagdfrow <- function(row, |
|
118 |
nm = obj_name(row), |
|
119 |
lab = obj_label(row), |
|
120 |
rnum, |
|
121 |
pth, |
|
122 |
sibpos = NA_integer_, |
|
123 |
nsibs = NA_integer_, |
|
124 |
extent = nlines(row, colwidths), |
|
125 |
colwidths = NULL, |
|
126 |
repext = 0L, |
|
127 |
repind = integer(), |
|
128 |
indent = 0L, |
|
129 |
rclass = class(row), |
|
130 |
nrowrefs = 0L, |
|
131 |
ncellrefs = 0L, |
|
132 |
nreflines = 0L, |
|
133 |
# ref_df = .make_ref_df(NULL, NULL), |
|
134 |
force_page = FALSE, |
|
135 |
page_title = NA_character_, |
|
136 |
trailing_sep = NA_character_) { |
|
137 | 1201x |
data.frame( |
138 | 1201x |
label = lab, |
139 | 1201x |
name = nm, |
140 | 1201x |
abs_rownumber = rnum, |
141 | 1201x |
path = I(list(pth)), |
142 | 1201x |
pos_in_siblings = sibpos, |
143 | 1201x |
n_siblings = nsibs, |
144 | 1201x |
self_extent = extent, |
145 | 1201x |
par_extent = repext, |
146 | 1201x |
reprint_inds = I(rep(list(unlist(repind)), length.out = length(nm))), |
147 | 1201x |
node_class = rclass, |
148 | 1201x |
indent = max(0L, indent), |
149 | 1201x |
nrowrefs = nrowrefs, |
150 | 1201x |
ncellrefs = ncellrefs, |
151 | 1201x |
nreflines = nreflines, |
152 |
# ref_info_df = I(list(ref_df)), |
|
153 | 1201x |
force_page = force_page, |
154 | 1201x |
page_title = page_title, |
155 | 1201x |
trailing_sep = trailing_sep, |
156 | 1201x |
stringsAsFactors = FALSE, |
157 | 1201x |
row.names = NULL, |
158 | 1201x |
check.names = FALSE, |
159 | 1201x |
fix.empty.names = FALSE |
160 |
) |
|
161 |
} |
|
162 | ||
163 | ||
164 |
calc_ref_nlines_df <- function(pagdf) { |
|
165 |
## XXX XXX XXX this is dangerous and wrong!!! |
|
166 | 401x |
if(is.null(pagdf$ref_info_df) && sum(pagdf$nreflines) == 0) |
167 | 156x |
return(ref_df_row()[0, ]) |
168 | 245x |
refdf <- do.call(rbind.data.frame, pagdf$ref_info_df) |
169 | 245x |
if(NROW(refdf) == 0) |
170 | 150x |
return(ref_df_row()[0, ]) |
171 | 95x |
unqsyms <- !duplicated(refdf$symbol) |
172 | 95x |
refdf[unqsyms, ,drop = FALSE] |
173 |
} |
|
174 | ||
175 | ||
176 |
build_fail_msg <- function(row, lines, raw_rowlines, |
|
177 |
start, guess, rep_ext, n_reprint, |
|
178 |
reflines, n_refs, sectlines) { |
|
179 | 249x |
if(row) { |
180 | 102x |
spacetype <- "lines" |
181 | 102x |
spacetype_abr <- "lns" |
182 | 102x |
structtype_abr <- "rws" |
183 | 102x |
sprintf("\t....................... FAIL: requires %d %s [raw: %d %s (%d %s), rep. context: %d %s (%d %s), refs: %d %s (%d) sect. divs: %d %s].", |
184 | 102x |
lines, |
185 | 102x |
spacetype, |
186 | 102x |
raw_rowlines, |
187 | 102x |
spacetype_abr, |
188 | 102x |
guess - start + 1, # because it includes both start and guess |
189 | 102x |
structtype_abr, |
190 | 102x |
rep_ext, |
191 | 102x |
spacetype_abr, |
192 | 102x |
n_reprint, |
193 | 102x |
structtype_abr, |
194 | 102x |
reflines, |
195 | 102x |
spacetype_abr, |
196 | 102x |
n_refs, |
197 | 102x |
sectlines, |
198 | 102x |
spacetype_abr) |
199 |
} else { ## !row |
|
200 | 147x |
spacetype <- "chars" |
201 | 147x |
spacetype_abr <- "chars" |
202 | 147x |
structtype_abr <- "cols" |
203 | 147x |
sprintf("\t....................... FAIL: requires %d %s (%d %s).", |
204 | 147x |
lines, |
205 | 147x |
spacetype, |
206 | 147x |
guess - start + 1, # because it includes both start and guess |
207 | 147x |
structtype_abr) |
208 |
} |
|
209 |
} |
|
210 | ||
211 |
valid_pag <- function(pagdf, |
|
212 |
guess, |
|
213 |
start, |
|
214 |
rlpp, |
|
215 |
min_sibs, |
|
216 |
nosplit = NULL, |
|
217 |
div_height = 1L, |
|
218 |
verbose = FALSE, |
|
219 |
row = TRUE, |
|
220 |
have_col_fnotes = FALSE) { |
|
221 | 401x |
rw <- pagdf[guess, ] |
222 | ||
223 | ||
224 | 401x |
if (verbose) { |
225 | 372x |
message( |
226 | 372x |
"Checking pagination after ", |
227 | 372x |
paste(ifelse(row, "row", "column"), guess) |
228 |
) |
|
229 |
} |
|
230 | 401x |
raw_rowlines <- sum(pagdf[start:guess, "self_extent"] - pagdf[start:guess, "nreflines"]) |
231 | ||
232 | 401x |
refdf_ii <- calc_ref_nlines_df(pagdf[start:guess,]) |
233 | 401x |
reflines <- if(row) sum(refdf_ii$nlines, 0L) else 0L |
234 | 401x |
if (reflines > 0 && !have_col_fnotes) |
235 | 32x |
reflines <- reflines + div_height + 1L |
236 | ||
237 |
## reflines <- sum(pagdf[start:guess, "nreflines"]) |
|
238 | 401x |
rowlines <- raw_rowlines + reflines ##sum(pagdf[start:guess, "self_extent"]) - reflines ## self extent includes reflines |
239 |
## self extent does ***not*** currently include trailing sep |
|
240 |
## we don't include the trailing_sep for guess because if we paginate here it won't be printed |
|
241 | 401x |
sectlines <- if (start == guess) 0L else sum(!is.na(pagdf[start:(guess - 1), "trailing_sep"])) |
242 | 401x |
lines <- rowlines + sectlines # guess - start + 1 because inclusive of start |
243 | 401x |
rep_ext <- pagdf$par_extent[start] |
244 | 401x |
if(lines > rlpp) { |
245 | 265x |
if(verbose) { |
246 | 249x |
structtype <- ifelse(row, "rows", "columns") |
247 | 249x |
structtype_abr <- ifelse(row, "rows", "cols") |
248 | 249x |
spacetype <- ifelse(row, "lines", "chars") |
249 | 249x |
spacetype_abr <- ifelse(row, "lns", "chrs") |
250 | 249x |
msg <- build_fail_msg(row, lines, raw_rowlines, start, guess, rep_ext, length(pagdf$reprint_inds[[start]]),reflines, NROW(refdf_ii), sectlines) |
251 | 249x |
message(msg) |
252 |
} |
|
253 | 265x |
return(FALSE) |
254 |
} |
|
255 | 136x |
if (rw[["node_class"]] %in% c("LabelRow", "ContentRow")) { |
256 | 5x |
if (verbose) { |
257 | 5x |
message("\t....................... FAIL: last row is a label or content row") |
258 |
} |
|
259 | 5x |
return(FALSE) |
260 |
} |
|
261 | ||
262 | 131x |
sibpos <- rw[["pos_in_siblings"]] |
263 | 131x |
nsib <- rw[["n_siblings"]] |
264 |
# okpos <- min(min_sibs + 1, rw[["n_siblings"]]) |
|
265 | 131x |
if (sibpos != nsib) { |
266 | 67x |
retfalse <- FALSE |
267 | 67x |
if (sibpos < min_sibs + 1) { |
268 | 25x |
retfalse <- TRUE |
269 | 25x |
if (verbose) { |
270 | 25x |
message( |
271 | 25x |
"\t....................... FAIL: last row had only ", sibpos - 1, |
272 | 25x |
" preceding siblings, needed ", min_sibs |
273 |
) |
|
274 |
} |
|
275 | 42x |
} else if (nsib - sibpos < min_sibs + 1) { |
276 | 4x |
retfalse <- TRUE |
277 | 4x |
if (verbose) { |
278 | 4x |
message( |
279 | 4x |
"\t....................... FAIL: last row had only ", nsib - sibpos - 1, |
280 | 4x |
" following siblings, needed ", min_sibs |
281 |
) |
|
282 |
} |
|
283 |
} |
|
284 | 67x |
if (retfalse) { |
285 | 29x |
return(FALSE) |
286 |
} |
|
287 |
} |
|
288 | 102x |
if (guess < nrow(pagdf) && length(nosplit > 0)) { |
289 |
## paths end at the leaf name which is *always* different |
|
290 | 16x |
curpth <- head(unlist(rw$path), -1) |
291 | 16x |
nxtpth <- head(unlist(pagdf$path[[guess + 1]]), -1) |
292 | ||
293 | 16x |
inplay <- nosplit[(nosplit %in% intersect(curpth, nxtpth))] |
294 | 16x |
if (length(inplay) > 0) { |
295 | 16x |
ok_split <- vapply(inplay, |
296 | 16x |
function(var) { |
297 | 16x |
!identical(curpth[match(var, curpth) + 1], |
298 | 16x |
nxtpth[match(var, nxtpth) + 1]) |
299 |
}, |
|
300 | 16x |
TRUE) |
301 | ||
302 | 16x |
curvals <- curpth[match(inplay, curpth) + 1] |
303 | 16x |
nxtvals <- nxtpth[match(inplay, nxtpth) + 1] |
304 | 16x |
if (!all(ok_split)) { |
305 | 16x |
if (verbose) { |
306 | 16x |
message( |
307 | 16x |
"\t....................... FAIL: nosplit variable [", |
308 | 16x |
inplay[min(which(!ok_split))], "] would be constant [", |
309 | 16x |
curvals, "] across this pagebreak.") |
310 |
} |
|
311 | 16x |
return(FALSE) |
312 |
} |
|
313 |
} |
|
314 |
} |
|
315 | 86x |
if (verbose) { |
316 | 73x |
message("\t....................... OK [", lines + rep_ext, if (row) " lines]" else " chars]") |
317 |
} |
|
318 | 86x |
TRUE |
319 |
} |
|
320 | ||
321 | ||
322 |
find_pag <- function(pagdf, |
|
323 |
start, |
|
324 |
guess, |
|
325 |
rlpp, |
|
326 |
min_siblings, |
|
327 |
nosplitin = character(), |
|
328 |
verbose = FALSE, |
|
329 |
row = TRUE, |
|
330 |
have_col_fnotes = FALSE, |
|
331 |
div_height = 1L) { |
|
332 | 91x |
origuess <- guess |
333 | 91x |
while (guess >= start && !valid_pag(pagdf, guess, |
334 | 91x |
start = start, rlpp = rlpp, min_sibs = min_siblings, |
335 | 91x |
nosplit = nosplitin, verbose, row = row, have_col_fnotes = have_col_fnotes, |
336 | 91x |
div_height = div_height |
337 |
)) { |
|
338 | 315x |
guess <- guess - 1 |
339 |
} |
|
340 | 91x |
if (guess < start) { |
341 | 5x |
stop("Unable to find any valid pagination between ", start, " and ", origuess) |
342 |
} |
|
343 | 86x |
guess |
344 |
} |
|
345 | ||
346 | ||
347 |
#' Find Pagination Indices From Pagination Info Dataframe |
|
348 |
#' |
|
349 |
#' Pagination methods should typically call the `make_row_df` method |
|
350 |
#' for their object and then call this function on the resulting |
|
351 |
#' pagination info data.frame. |
|
352 |
#' |
|
353 |
#' @details `pab_indices_inner` implements the Core Pagination Algorithm |
|
354 |
#' for a single direction (vertical if `row = TRUE`, the default, horizontal otherwise) |
|
355 |
#' based on the pagination dataframe and (already adjusted for non-body rows/columns) |
|
356 |
#' lines (or characters) per page. |
|
357 |
#' |
|
358 |
#' @inheritSection pagination_algo Pagination Algorithm |
|
359 |
#' @param pagdf data.frame. A pagination info data.frame as created by |
|
360 |
#' either `make_rows_df` or `make_cols_df`. |
|
361 |
#' @param rlpp numeric. Maximum number of \emph{row} lines per page (not including header materials), including |
|
362 |
#' (re)printed header and context rows |
|
363 |
#' @param min_siblings numeric. Minimum sibling rows which must appear on either side of pagination row for a |
|
364 |
#' mid-subtable split to be valid. Defaults to 2. |
|
365 |
#' @param nosplitin character. List of names of sub-tables where page-breaks are not allowed, regardless of other |
|
366 |
#' considerations. Defaults to none. |
|
367 |
#' @param verbose logical(1). Should additional informative messages about the search for |
|
368 |
#' pagination breaks be shown. Defaults to \code{FALSE}. |
|
369 |
#' @param row logical(1). Is pagination happening in row |
|
370 |
#' space (`TRUE`, the default) or column space (`FALSE`) |
|
371 |
#' @param have_col_fnotes logical(1). Does the table-like object being rendered have |
|
372 |
#' column-associated referential footnotes. |
|
373 |
#' @param div_height numeric(1). The height of the divider line when the |
|
374 |
#' associated object is rendered. Defaults to `1`. |
|
375 |
#' @return A list containing the vector of row numbers, broken up by page |
|
376 |
#' |
|
377 |
#' @examples |
|
378 |
#' mypgdf <- basic_pagdf(row.names(mtcars)) |
|
379 |
#' |
|
380 |
#' paginds <- pag_indices_inner(mypgdf, rlpp = 15, min_siblings = 0) |
|
381 |
#' lapply(paginds, function(x) mtcars[x, ]) |
|
382 |
#' |
|
383 |
#' @export |
|
384 |
pag_indices_inner <- function(pagdf, rlpp, |
|
385 |
min_siblings, |
|
386 |
nosplitin = character(), |
|
387 |
verbose = FALSE, |
|
388 |
row = TRUE, |
|
389 |
have_col_fnotes = FALSE, |
|
390 |
div_height = 1L) { |
|
391 | 37x |
start <- 1 |
392 | 37x |
nr <- nrow(pagdf) |
393 | 37x |
ret <- list() |
394 | 37x |
while (start <= nr) { |
395 | 92x |
adjrlpp <- rlpp - pagdf$par_extent[start] |
396 | 92x |
if (adjrlpp <= 0) { |
397 | 1x |
if (row) { |
398 | 1x |
stop("Lines of repeated context (plus header materials) larger than specified lines per page") |
399 |
} else { |
|
400 | ! |
stop("Width of row labels equal to or larger than specified characters per page.") |
401 |
} |
|
402 |
} |
|
403 | 91x |
guess <- min(nr, start + adjrlpp - 1) |
404 | 91x |
end <- find_pag(pagdf, start, guess, |
405 | 91x |
rlpp = adjrlpp, |
406 | 91x |
min_siblings = min_siblings, |
407 | 91x |
nosplitin = nosplitin, |
408 | 91x |
verbose = verbose, |
409 | 91x |
row = row, |
410 | 91x |
have_col_fnotes = have_col_fnotes, |
411 | 91x |
div_height = div_height |
412 |
) |
|
413 | 86x |
ret <- c(ret, list(c( |
414 | 86x |
pagdf$reprint_inds[[start]], |
415 | 86x |
start:end |
416 |
))) |
|
417 | 86x |
start <- end + 1 |
418 |
} |
|
419 | 31x |
ret |
420 |
} |
|
421 | ||
422 |
#' Find Column Indices for Vertical Pagination |
|
423 |
#' @param obj ANY. object to be paginated. Must have a |
|
424 |
#' \code{\link{matrix_form}} method. |
|
425 |
#' @param cpp numeric(1). Number of characters per page (width) |
|
426 |
#' @param colwidths numeric vector. Column widths (in characters) for |
|
427 |
#' use with vertical pagination. |
|
428 |
#' @param rep_cols numeric(1). Number of \emph{columns} (not including |
|
429 |
#' row labels) to be repeated on every page. Defaults to 0 |
|
430 |
#' @inheritParams pag_indices_inner |
|
431 |
#' |
|
432 |
#' @return A list partitioning the vector of column indices |
|
433 |
#' into subsets for 1 or more horizontally paginated pages. |
|
434 |
#' |
|
435 |
#' @examples |
|
436 |
#' mf <- basic_matrix_form(df = mtcars) |
|
437 |
#' colpaginds <- vert_pag_indices(mf) |
|
438 |
#' lapply(colpaginds, function(j) mtcars[, j, drop = FALSE]) |
|
439 |
#' @export |
|
440 |
vert_pag_indices <- function(obj, cpp = 40, colwidths = NULL, verbose = FALSE, rep_cols = 0L) { |
|
441 | 16x |
mf <- matrix_form(obj, TRUE) |
442 | 16x |
clwds <- colwidths %||% propose_column_widths(mf) |
443 | 16x |
if(is.null(mf_cinfo(mf))) ## like always, ugh. |
444 | 2x |
mf <- mpf_infer_cinfo(mf, colwidths = clwds, rep_cols = rep_cols) |
445 | ||
446 | 16x |
has_rlabs <- mf_has_rlabels(mf) |
447 | 16x |
rlabs_flag <- as.integer(has_rlabs) |
448 | 16x |
rlab_extent <- if (has_rlabs) clwds[1] else 0L |
449 | ||
450 |
# rep_extent <- pdf$par_extent[nrow(pdf)] |
|
451 | 16x |
rcpp <- cpp - table_inset(mf) - rlab_extent # rep_extent - table_inset(mf) - rlab_extent |
452 | 16x |
if (verbose) { |
453 | 12x |
message( |
454 | 12x |
"Adjusted characters per page: ", rcpp, |
455 | 12x |
" [original: ", cpp, |
456 | 12x |
", table inset: ", table_inset(mf), if (has_rlabs) paste0(", row labels: ", clwds[1]), |
457 |
"]" |
|
458 |
) |
|
459 |
} |
|
460 | 16x |
res <- pag_indices_inner(mf_cinfo(mf), |
461 | 16x |
rlpp = rcpp, # cpp - sum(clwds[seq_len(rep_cols)]), |
462 | 16x |
verbose = verbose, |
463 | 16x |
min_siblings = 1, |
464 | 16x |
row = FALSE |
465 |
) |
|
466 | 16x |
res |
467 |
} |
|
468 | ||
469 |
mpf_infer_cinfo <- function(mf, colwidths = NULL, rep_cols = num_rep_cols(mf)) { |
|
470 | ||
471 | 46x |
if (!is(rep_cols, "numeric") || is.na(rep_cols) || rep_cols < 0) { |
472 | ! |
stop("got invalid number of columns to be repeated: ", rep_cols) |
473 |
} |
|
474 | 46x |
clwds <- (colwidths %||% mf_col_widths(mf)) %||% propose_column_widths(mf) |
475 | 46x |
has_rlabs <- mf_has_rlabels(mf) |
476 | 46x |
rlabs_flag <- as.integer(has_rlabs) |
477 | 46x |
rlab_extent <- if (has_rlabs) clwds[1] else 0L |
478 | 46x |
sqstart <- rlabs_flag + 1L # rep_cols + 1L |
479 | ||
480 | 46x |
pdfrows <- lapply( |
481 | 46x |
(sqstart):ncol(mf$strings), |
482 | 46x |
function(i) { |
483 | 494x |
rownum <- i - rlabs_flag |
484 | 494x |
rep_inds <- seq_len(rep_cols)[seq_len(rep_cols) < rownum] |
485 | 494x |
rep_extent_i <- sum(0L, clwds[rlabs_flag + rep_inds]) + mf$col_gap * length(rep_inds) |
486 | 494x |
pagdfrow( |
487 | 494x |
row = NA, |
488 | 494x |
nm = rownum, |
489 | 494x |
lab = rownum, |
490 | 494x |
rnum = rownum, |
491 | 494x |
pth = NA, |
492 | 494x |
extent = clwds[i] + mf$col_gap, |
493 | 494x |
repext = rep_extent_i, # sum(clwds[rep_cols]) + mf$col_gap * max(0, (length(rep_cols) - 1)), |
494 | 494x |
repind = rep_inds, # rep_cols, |
495 | 494x |
rclass = "stuff", |
496 | 494x |
sibpos = 1 - 1, |
497 | 494x |
nsibs = 1 - 1 |
498 |
) |
|
499 |
} |
|
500 |
) |
|
501 | 46x |
pdf <- do.call(rbind, pdfrows) |
502 | ||
503 | 46x |
refdf <- mf_fnote_df(mf) |
504 | 46x |
pdf <- splice_fnote_info_in(pdf, refdf, row = FALSE) |
505 | 46x |
mf_cinfo(mf) <- pdf |
506 | 46x |
mf |
507 |
} |
|
508 | ||
509 | ||
510 |
#' Basic/spoof pagination info dataframe |
|
511 |
#' |
|
512 |
#' Returns a minimal pagination info data.frame (with no sibling/footnote/etc info). |
|
513 |
#' @inheritParams basic_matrix_form |
|
514 |
#' @param rnames character. Vector of row names |
|
515 |
#' @param labs character. Vector of row labels (defaults to names) |
|
516 |
#' @param rnums integer. Vector of row numbers. Defaults to `seq_along(rnames)`. |
|
517 |
#' @param extents integer. Number of lines each row will take to print, defaults to 1 for all rows |
|
518 |
#' @param rclass character. Class(es) for the rows. Defaults to "NA" |
|
519 |
#' |
|
520 |
#' @return A data.frame suitable for use in both the `matrix_print_form` constructor and the pagination machinery |
|
521 |
#' |
|
522 |
#' @examples |
|
523 |
#' |
|
524 |
#' basic_pagdf(c("hi", "there")) |
|
525 |
#' @export |
|
526 |
basic_pagdf <- function(rnames, labs = rnames, rnums = seq_along(rnames), |
|
527 |
extents = 1L, |
|
528 |
rclass = "NA", |
|
529 |
parent_path = "root") { |
|
530 | 26x |
rws <- mapply(pagdfrow, |
531 | 26x |
nm = rnames, lab = labs, extent = extents, |
532 | 26x |
rclass = rclass, rnum = rnums, pth = lapply(rnames, function(x) c(parent_path, x)), |
533 | 26x |
SIMPLIFY = FALSE, nsibs = 1, sibpos = 1 |
534 |
) |
|
535 | 26x |
res <- do.call(rbind.data.frame, rws) |
536 | 26x |
res$n_siblings <- nrow(res) |
537 | 26x |
res$pos_in_siblings <- seq_along(res$n_siblings) |
538 | 26x |
res |
539 |
} |
|
540 | ||
541 | ||
542 | ||
543 | ||
544 |
## write paginate() which operates **solely** on a MatrixPrintForm obj |
|
545 | ||
546 | ||
547 |
page_size_spec <- function(lpp, cpp, max_width) { |
|
548 | 21x |
structure(list(lpp = lpp, |
549 | 21x |
cpp = cpp, |
550 | 21x |
max_width = max_width), |
551 | 21x |
class = "page_size_spec") |
552 |
} |
|
553 | ||
554 | ||
555 | 42x |
non_null_na <- function(x) !is.null(x) && is.na(x) |
556 | ||
557 | ||
558 |
calc_lcpp <- function(page_type = NULL, |
|
559 |
landscape = FALSE, |
|
560 |
pg_width = page_dim(page_type)[if(landscape) 2 else 1], |
|
561 |
pg_height = page_dim(page_type)[if(landscape) 1 else 2], |
|
562 |
font_family = "Courier", |
|
563 |
font_size = 8, # grid parameters |
|
564 |
cpp = NA_integer_, |
|
565 |
lpp = NA_integer_, |
|
566 |
tf_wrap = TRUE, |
|
567 |
max_width = NULL, |
|
568 |
lineheight = 1, |
|
569 |
margins = c(bottom = .5, left = .75, top = .5, right = .75), |
|
570 |
colwidths, |
|
571 |
col_gap, |
|
572 |
inset |
|
573 |
) { |
|
574 | ||
575 | 21x |
pg_lcpp <- page_lcpp(page_type = page_type, |
576 | 21x |
landscape = landscape, |
577 | 21x |
font_family = font_family, |
578 | 21x |
font_size = font_size, |
579 | 21x |
lineheight = lineheight, |
580 | 21x |
margins = margins, |
581 | 21x |
pg_width = pg_width, |
582 | 21x |
pg_height = pg_height) |
583 | ||
584 | 21x |
if (non_null_na(lpp)) { |
585 | 13x |
lpp <- pg_lcpp$lpp |
586 |
} |
|
587 | 21x |
if(non_null_na(cpp)) { |
588 | 14x |
cpp <- pg_lcpp$cpp |
589 |
} |
|
590 | 21x |
stopifnot(!is.na(cpp)) |
591 | 21x |
if(!tf_wrap && !is.null(max_width)) { |
592 | ! |
warning("tf_wrap is FALSE - ignoring non-null max_width value.") |
593 | ! |
max_width <- NULL |
594 | 21x |
} else if(tf_wrap && is.null(max_width)) |
595 | 5x |
max_width <- cpp |
596 | ||
597 | 21x |
if(is.character(max_width) && identical(max_width, "auto")) { |
598 | ! |
max_width <- inset + sum(colwidths) + (length(colwidths) - 1) * col_gap |
599 |
} |
|
600 | 21x |
page_size_spec(lpp = lpp, cpp = cpp, max_width = max_width) |
601 |
} |
|
602 | ||
603 | ||
604 |
calc_rlpp <- function(pg_size_spec, mf, colwidths, tf_wrap, verbose) { |
|
605 | 19x |
lpp <- pg_size_spec$lpp |
606 | 19x |
max_width = pg_size_spec$max_width |
607 | ||
608 | 19x |
dh <- divider_height(mf) |
609 | 19x |
if (any(nzchar(all_titles(mf)))) { |
610 |
## +1 is for blank line between subtitles and divider |
|
611 |
## dh is for divider line **between subtitles and column labels** |
|
612 |
## other divider line is accounted for in cinfo_lines |
|
613 | 11x |
if(!tf_wrap) |
614 | 9x |
tlines <- length(all_titles(mf)) |
615 |
else |
|
616 | 2x |
tlines <- sum(nlines(all_titles(mf), colwidths = colwidths, |
617 | 2x |
max_width = max_width)) |
618 | 11x |
tlines <- tlines + dh + 1L |
619 |
} else { |
|
620 | 8x |
tlines <- 0 |
621 |
} |
|
622 | ||
623 |
## dh for divider line between column labels and table body |
|
624 | 19x |
cinfo_lines <- mf_nlheader(mf) + dh |
625 | ||
626 | 19x |
if(verbose) |
627 | 15x |
message("Determining lines required for header content: ", |
628 | 15x |
tlines, " title and ", cinfo_lines, " table header lines") |
629 | ||
630 | 19x |
refdf <- mf_fnote_df(mf) |
631 | 19x |
cfn_df <- refdf[is.na(refdf$row) & !is.na(refdf$col),] |
632 | ||
633 | 19x |
flines <- 0L |
634 | 19x |
mnfoot <- main_footer(mf) |
635 | 19x |
havemn <- length(mnfoot) && any(nzchar(mnfoot)) |
636 | 19x |
if(havemn) |
637 | 12x |
flines <- nlines(mnfoot, colwidths = colwidths, |
638 | 12x |
max_width = max_width - table_inset(mf)) |
639 | 19x |
prfoot <- prov_footer(mf) |
640 | 19x |
if(length(prfoot) && any(nzchar(prfoot))) { |
641 | 11x |
flines <- flines + nlines(prov_footer(mf), colwidths = colwidths, max_width = max_width) |
642 | 11x |
if(havemn) |
643 | 11x |
flines <- flines + 1L ## space between main and prov footer. |
644 |
} |
|
645 |
## this time its for the divider between the footers and whatever is above them |
|
646 |
## (either table body or referential footnotes) |
|
647 | 19x |
if(flines > 0) |
648 | 12x |
flines <- flines + dh + 1L |
649 |
## this time its for the divider between the referential footnotes and |
|
650 |
## the table body IFF we have any, otherwise that divider+blanks pace doesn't get drawn |
|
651 | 19x |
if(NROW(cfn_df) > 0) { |
652 | ! |
cinfo_lines <- cinfo_lines + sum(cfn_df$nlines) |
653 | ! |
flines <- flines + dh + 1L |
654 |
} |
|
655 | ||
656 | 19x |
if(verbose) |
657 | 15x |
message("Determining lines required for footer content", |
658 | 15x |
if(NROW(cfn_df) > 0) " [column fnotes present]", |
659 | 15x |
": ", flines, " lines") |
660 | ||
661 | 19x |
ret <- lpp - flines - tlines - cinfo_lines |
662 | ||
663 | 19x |
if(verbose) |
664 | 15x |
message("Lines per page available for tables rows: ", ret, " (original: ", lpp, ")") |
665 | 19x |
ret |
666 |
} |
|
667 | ||
668 | ||
669 |
calc_rcpp <- function(pg_size_spec, mf, colwidths) { |
|
670 | ||
671 | ! |
cpp <- pg_size_spec$cpp |
672 | ||
673 | ! |
cpp - table_inset(mf) - colwidths[1] - mf_colgap(mf) |
674 |
} |
|
675 | ||
676 | ||
677 |
splice_idx_lists <- function(lsts) { |
|
678 | ! |
list(pag_row_indices = do.call(c, lapply(lsts, function(xi) xi$pag_row_indices)), |
679 | ! |
pag_col_indices = do.call(c, lapply(lsts, function(yi) yi$pag_col_indices))) |
680 | ||
681 |
} |
|
682 | ||
683 | ||
684 | ||
685 |
#' @title Paginate a table-like object for rendering |
|
686 |
#' |
|
687 |
#' @description |
|
688 |
#' These functions perform or diagnose bi-directional pagination on |
|
689 |
#' an object. |
|
690 |
#' |
|
691 |
#' `paginate_to_mpfs` renders `obj` into the `MatrixPrintForm` (`MPF`) |
|
692 |
#' intermediate representation, and then paginates that `MPF` into |
|
693 |
#' component `MPF`s each corresponding to an individual page and |
|
694 |
#' returns those in a list. |
|
695 |
#' |
|
696 |
#' `paginate_indices` renders `obj` into an `MPF`, then uses |
|
697 |
#' that representation to calculate the rows and columns of |
|
698 |
#' `obj` corresponding to each page of the pagination of `obj`, |
|
699 |
#' but simply returns these indices rather than paginating |
|
700 |
#' \code{obj} itself (see details for an important caveat). |
|
701 |
#' |
|
702 |
#' `diagnose_pagination` attempts pagination via `paginate_to_mpfs` |
|
703 |
#' and then returns diagnostic information which explains why page |
|
704 |
#' breaks were positioned where they were, or alternatively why |
|
705 |
#' no valid paginations could be found. |
|
706 |
#' |
|
707 |
#' @details |
|
708 |
#' |
|
709 |
#' All three of these functions generally support all classes which have |
|
710 |
#' a corresponding `matrix_form` method which returns a valid `MatrixPrintForm` |
|
711 |
#' object (including `MatrixPrintForm` objects themselves). |
|
712 |
#' |
|
713 |
#' `paginate_indices` is directly called by `paginate_to_mpfs` (and thus |
|
714 |
#' `diagnose_pagination`). For most classes, and most tables represented |
|
715 |
#' by supported classes, calling `paginate_to_mpfs` is equivalent to a |
|
716 |
#' manual `paginate_indices -> subset obj into pages -> matrix_form` |
|
717 |
#' workflow. |
|
718 |
#' |
|
719 |
#' The exception to this equivalence is objects which support 'forced pagination', |
|
720 |
#' or pagination logic which built into the object itself rather than being a |
|
721 |
#' function of space on a page. Forced pagination generally involves the creation |
|
722 |
#' of, e.g., page-specific titles which apply to these forced paginations. |
|
723 |
#' `paginate_to_mpfs` and `diagnose_pagination` support forced pagination by |
|
724 |
#' automatically calling the `do_forced_pagination` generic on the object |
|
725 |
#' and then paginating each object returned by that generic separately. The |
|
726 |
#' assumption here, then, is that page-specific titles and such are |
|
727 |
#' handled by the class' `do_forced_pagination` method. |
|
728 |
#' |
|
729 |
#' `paginate_indices`, on the other hand, \emph{does not support forced pagination}, |
|
730 |
#' because it returns only a set of indices for row and column subsetting for each page, |
|
731 |
#' and thus cannot retain any changes, e.g., to titles, done within `do_forced_paginate`. |
|
732 |
#' `paginate_indices` does call `do_forced_paginate`, but instead of continuing, it |
|
733 |
#' throws an error in the case that the result is more than a single "page". |
|
734 |
#' |
|
735 |
#' @inheritParams vert_pag_indices |
|
736 |
#' @inheritParams pag_indices_inner |
|
737 |
#' @inheritParams page_lcpp |
|
738 |
#' @inheritParams toString |
|
739 |
#' @inheritParams propose_column_widths |
|
740 |
#' @param lpp numeric(1) or NULL. Lines per page. if NA (the default, |
|
741 |
#' this is calculated automatically based on the specified page |
|
742 |
#' size). `NULL` indicates no vertical pagination should occur. |
|
743 |
#' @param cpp numeric(1) or NULL. Width in characters per page. if NA (the default, |
|
744 |
#' this is calculated automatically based on the specified page |
|
745 |
#' size). `NULL` indicates no horizontal pagination should occur. |
|
746 | ||
747 |
#' @param pg_size_spec page_size_spec. A pre-calculated page |
|
748 |
#' size specification. Typically this is not set in end user code. |
|
749 |
#' @param col_gap numeric(1). Currently unused. |
|
750 |
#' @return for `paginate_indices` a list with two elements of the same |
|
751 |
#' length: `pag_row_indices`, and `pag_col_indices`. For |
|
752 |
#' `paginate_to_mpfs`, a list of `MatrixPrintForm` objects |
|
753 |
#' representing each individual page after pagination (including |
|
754 |
#' forced pagination if necessary). |
|
755 |
#' @export |
|
756 |
#' @aliases paginate pagination |
|
757 |
#' @examples |
|
758 |
#' mpf <- basic_matrix_form(mtcars) |
|
759 |
#' |
|
760 |
#' paginate_indices(mpf, pg_width = 5, pg_height = 3) |
|
761 |
#' |
|
762 |
#' paginate_to_mpfs(mpf, pg_width = 5, pg_height = 3) |
|
763 |
paginate_indices <- function(obj, |
|
764 |
page_type = "letter", |
|
765 |
font_family = "Courier", |
|
766 |
font_size = 8, |
|
767 |
lineheight = 1, |
|
768 |
landscape = FALSE, |
|
769 |
pg_width = NULL, |
|
770 |
pg_height = NULL, |
|
771 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
772 |
lpp = NA_integer_, |
|
773 |
cpp = NA_integer_, |
|
774 |
min_siblings = 2, |
|
775 |
nosplitin = character(), |
|
776 |
colwidths = NULL, |
|
777 |
tf_wrap = FALSE, |
|
778 |
max_width = NULL, |
|
779 |
indent_size = 2, |
|
780 |
pg_size_spec = NULL, |
|
781 |
rep_cols = num_rep_cols(obj), |
|
782 |
col_gap = 3, |
|
783 |
verbose = FALSE) { |
|
784 | ||
785 | ||
786 |
## this MUST alsways return a list, inluding list(obj) when |
|
787 |
## no forced pagination is needed! otherwise stuff breaks for things |
|
788 |
## based on s3 classes that are lists underneath!!! |
|
789 | 21x |
fpags <- do_forced_paginate(obj) |
790 | ||
791 |
## if we have more than one forced "page", |
|
792 |
## paginate each of them individually and return the result. |
|
793 |
## forced pagination is ***currently*** only vertical, so |
|
794 |
## we don't have to worry about divying up colwidths here, |
|
795 |
## but we will if we ever allow force_paginate to do horiz |
|
796 |
## pagination. |
|
797 | 21x |
if(length(fpags) > 1) { |
798 | 1x |
stop("forced pagination is required for this object (class: ", class(obj)[1], |
799 | 1x |
") this is not supported in paginate_indices. Use paginate_to_mpfs or call ", |
800 | 1x |
"do_forced_paginate on your object and paginate each returned section separately.") |
801 |
} |
|
802 | ||
803 | ||
804 |
## I'm not sure this is worth doing. |
|
805 |
## ## We can't support forced pagination here, but we can support calls to, |
|
806 |
## ## e.g., paginate_indices(do_forced_pag(tt)) |
|
807 |
## if(is.list(obj) && !is.object(obj)) { |
|
808 |
## res <- lapply(obj, paginate_indices, |
|
809 |
## page_type = page_type, |
|
810 |
## font_family = font_family, |
|
811 |
## font_size = font_size, |
|
812 |
## lineheight = lineheight, |
|
813 |
## landscape = landscape, |
|
814 |
## pg_width = pg_width, |
|
815 |
## pg_height = pg_height, |
|
816 |
## margins = margins, |
|
817 |
## lpp = lpp, |
|
818 |
## cpp = cpp, |
|
819 |
## tf_wrap = tf_wrap, |
|
820 |
## max_width = max_width, |
|
821 |
## colwidths = colwidths, |
|
822 |
## min_siblings = min_siblings, |
|
823 |
## nosplitin = nosplitin, |
|
824 |
## col_gap = col_gap, |
|
825 |
## ## not setting num_rep_cols here cause it wont' get it right |
|
826 |
## verbose = verbose) |
|
827 |
## return(splice_idx_lists(res)) |
|
828 |
## } |
|
829 |
## order is annoying here, since we won't actually need the mpf if |
|
830 |
## we run into forced pagination, but life is short and this should work fine. |
|
831 | 20x |
mpf <- matrix_form(obj, TRUE, TRUE, indent_size = indent_size) |
832 | 20x |
if(is.null(colwidths)) |
833 | 2x |
colwidths <- mf_col_widths(mpf) %||% propose_column_widths(mpf) |
834 |
else |
|
835 | 18x |
mf_col_widths(mpf) <- colwidths |
836 | 20x |
if(NROW(mf_cinfo(mpf)) == 0) |
837 | 20x |
mpf <- mpf_infer_cinfo(mpf, colwidths, rep_cols) |
838 | ||
839 | ||
840 | 20x |
if(is.null(pg_size_spec)) { |
841 | 2x |
pg_size_spec <- calc_lcpp(page_type = page_type, |
842 | 2x |
font_family = font_family, |
843 | 2x |
font_size = font_size, |
844 | 2x |
lineheight = lineheight, |
845 | 2x |
landscape = landscape, |
846 | 2x |
pg_width = pg_width, |
847 | 2x |
pg_height = pg_height, |
848 | 2x |
margins = margins, |
849 | 2x |
lpp = lpp, |
850 | 2x |
cpp = cpp, |
851 | 2x |
tf_wrap = tf_wrap, |
852 | 2x |
max_width = max_width, |
853 | 2x |
colwidths = colwidths, |
854 | 2x |
inset = table_inset(mpf), |
855 | 2x |
col_gap = col_gap) |
856 |
} |
|
857 | ||
858 |
## we can't support forced pagination in paginate_indices because |
|
859 |
## forced pagination is generally going to set page titles, which |
|
860 |
## we can't preserve when just returning lists of indices. |
|
861 |
## Instead we make a hard assumption here that any forced pagination |
|
862 |
## has already occured. |
|
863 | ||
864 | ||
865 | ||
866 | ||
867 | ||
868 |
## this wraps the cell contents AND shoves referential footnote |
|
869 |
## info into mf_rinfo(mpf) |
|
870 | 20x |
mpf <- do_cell_fnotes_wrap(mpf, colwidths, max_width, tf_wrap = tf_wrap) |
871 | ||
872 | 20x |
if(is.null(pg_size_spec$lpp)) |
873 | 1x |
pag_row_indices <- list(seq_len(mf_nrow(mpf))) |
874 |
else |
|
875 | 19x |
pag_row_indices <- pag_indices_inner(pagdf= mf_rinfo(mpf), |
876 | 19x |
rlpp = calc_rlpp(pg_size_spec, mpf, colwidths = colwidths, tf_wrap = tf_wrap, |
877 | 19x |
verbose = verbose), |
878 | 19x |
verbose = verbose, |
879 | 19x |
min_siblings = min_siblings, |
880 | 19x |
nosplitin = nosplitin) |
881 | ||
882 | 15x |
if(is.null(pg_size_spec$cpp)) |
883 | 1x |
pag_col_indices <- list(seq_len(mf_ncol(mpf))) |
884 |
else |
|
885 | 14x |
pag_col_indices <- vert_pag_indices(mpf, cpp = pg_size_spec$cpp, colwidths = colwidths, |
886 | 14x |
rep_cols = rep_cols, verbose = verbose) |
887 | ||
888 | 15x |
list(pag_row_indices = pag_row_indices, |
889 | 15x |
pag_col_indices = pag_col_indices) |
890 |
} |
|
891 | ||
892 | 18x |
setGeneric("has_page_title", function(obj) standardGeneric("has_page_title")) |
893 | ||
894 | 18x |
setMethod("has_page_title", "ANY", function(obj) length(page_titles(obj)) > 0) |
895 | ||
896 |
#' @rdname paginate_indices |
|
897 |
#' @export |
|
898 |
paginate_to_mpfs <- function(obj, |
|
899 |
page_type = "letter", |
|
900 |
font_family = "Courier", |
|
901 |
font_size = 8, |
|
902 |
lineheight = 1, |
|
903 |
landscape = FALSE, |
|
904 |
pg_width = NULL, |
|
905 |
pg_height = NULL, |
|
906 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
907 |
lpp = NA_integer_, |
|
908 |
cpp = NA_integer_, |
|
909 |
min_siblings = 2, |
|
910 |
nosplitin = character(), |
|
911 |
colwidths = NULL, |
|
912 |
tf_wrap = FALSE, |
|
913 |
max_width = NULL, |
|
914 |
indent_size = 2, |
|
915 |
pg_size_spec = NULL, |
|
916 |
rep_cols = num_rep_cols(obj), |
|
917 |
col_gap = 2, |
|
918 |
verbose = FALSE) { |
|
919 | ||
920 | 19x |
mpf <- matrix_form(obj, TRUE, TRUE, indent_size = indent_size) |
921 | 19x |
if(is.null(colwidths)) |
922 | 11x |
colwidths <- mf_col_widths(mpf) %||% propose_column_widths(mpf) |
923 |
else |
|
924 | 8x |
mf_col_widths(mpf) <- colwidths |
925 | 19x |
if(NROW(mf_cinfo(mpf)) == 0) |
926 | 19x |
mpf <- mpf_infer_cinfo(mpf, colwidths, rep_cols) |
927 | ||
928 | ||
929 | 19x |
if(is.null(pg_size_spec)) { |
930 | 17x |
pg_size_spec <- calc_lcpp(page_type = page_type, |
931 | 17x |
font_family = font_family, |
932 | 17x |
font_size = font_size, |
933 | 17x |
lineheight = lineheight, |
934 | 17x |
landscape = landscape, |
935 | 17x |
pg_width = pg_width, |
936 | 17x |
pg_height = pg_height, |
937 | 17x |
margins = margins, |
938 | 17x |
lpp = lpp, |
939 | 17x |
cpp = cpp, |
940 | 17x |
tf_wrap = tf_wrap, |
941 | 17x |
max_width = max_width, |
942 | 17x |
colwidths = colwidths, |
943 | 17x |
inset = table_inset(mpf), |
944 | 17x |
col_gap = col_gap) |
945 |
} |
|
946 |
## this MUST alsways return a list, inluding list(obj) when |
|
947 |
## no forced pagination is needed! otherwise stuff breaks for things |
|
948 |
## based on s3 classes that are lists underneath!!! |
|
949 | 19x |
fpags <- do_forced_paginate(obj) |
950 | ||
951 |
## if we have more than one forced "page", |
|
952 |
## paginate each of them individually and return the result. |
|
953 |
## forced pagination is ***currently*** only vertical, so |
|
954 |
## we don't have to worry about divying up colwidths here, |
|
955 |
## but we will if we ever allow force_paginate to do horiz |
|
956 |
## pagination. |
|
957 | 19x |
if(length(fpags) > 1) { |
958 | 1x |
deep_pag <- lapply(fpags, paginate_to_mpfs, |
959 | 1x |
pg_size_spec = pg_size_spec, |
960 | 1x |
colwidths = colwidths, |
961 | 1x |
min_siblings = min_siblings, |
962 | 1x |
nosplitin = nosplitin, |
963 | 1x |
verbose = verbose) |
964 | 1x |
return(unlist(deep_pag, recursive = FALSE)) |
965 | 18x |
} else if (has_page_title(fpags[[1]])) { |
966 | ! |
obj <- fpags[[1]] |
967 |
} |
|
968 | ||
969 | ||
970 |
## we run into forced pagination, but life is short and this should work fine. |
|
971 | 18x |
mpf <- matrix_form(obj, TRUE, TRUE, indent_size = indent_size) |
972 | 18x |
if(is.null(colwidths)) |
973 | ! |
colwidths <- mf_col_widths(mpf) %||% propose_column_widths(mpf) |
974 | 18x |
mf_col_widths(mpf) <- colwidths |
975 | ||
976 | 18x |
page_indices <- paginate_indices(obj = obj, |
977 |
## page_type = page_type, |
|
978 |
## font_family = font_family, |
|
979 |
## font_size = font_size, |
|
980 |
## lineheight = lineheight, |
|
981 |
## landscape = landscape, |
|
982 |
## pg_width = pg_width, |
|
983 |
## pg_height = pg_height, |
|
984 |
## margins = margins, |
|
985 | 18x |
pg_size_spec = pg_size_spec, |
986 |
## lpp = lpp, |
|
987 |
## cpp = cpp, |
|
988 | 18x |
min_siblings = min_siblings, |
989 | 18x |
nosplitin = nosplitin, |
990 | 18x |
colwidths = colwidths, |
991 | 18x |
tf_wrap = tf_wrap, |
992 |
## max_width = max_width, |
|
993 | 18x |
rep_cols = rep_cols, |
994 | 18x |
verbose = verbose) |
995 | ||
996 | 15x |
pagmats <- lapply(page_indices$pag_row_indices, function(ii) { |
997 | 34x |
mpf_subset_rows(mpf, ii) |
998 |
}) |
|
999 | ||
1000 |
## these chunks now carry around their (correctly subset) col widths... |
|
1001 | 15x |
res <- lapply(pagmats, function(matii) { |
1002 | 34x |
lapply(page_indices$pag_col_indices, function(jj) { |
1003 | 68x |
mpf_subset_cols(matii, jj) |
1004 |
}) |
|
1005 |
}) |
|
1006 | 15x |
unlist(res, recursive = FALSE) |
1007 |
} |
|
1008 | ||
1009 | ||
1010 |
#' @importFrom utils capture.output |
|
1011 |
#' @details |
|
1012 |
#' |
|
1013 |
#' `diagnose_pagination` attempts pagination and then, regardless of success |
|
1014 |
#' or failure, returns diagnostic information about pagination |
|
1015 |
#' attempts (if any) after each row and column. |
|
1016 |
#' |
|
1017 |
#' The diagnostics data reflects the final time the pagination algorithm |
|
1018 |
#' evaluated a page break at the specified location, regardless of how |
|
1019 |
#' many times the position was assessed total. |
|
1020 |
#' |
|
1021 |
#' To get information about intermediate attempts, perform pagination |
|
1022 |
#' with `verbose = TRUE` and inspect the messages in order. |
|
1023 |
#' |
|
1024 |
#' @return For `diagnose_pagination` a list containing: |
|
1025 |
#' |
|
1026 |
#' \describe{ |
|
1027 |
#' \item{`lpp_diagnostics`}{diagnostic information regarding lines per page} |
|
1028 |
#' \item{`row_diagnostics`}{basic information about rows, whether pagination was attempted after each row, and the final result of such an attempt, if made} |
|
1029 |
#' \item{`cpp_diagnostics}{diagnostic information regarding columns per page} |
|
1030 |
#' \item{`col_diagnostics`}{(very) basic information about leaf columns, whether pagination was attempted after each leaf column, ad the final result of such attempts, if made} |
|
1031 |
#' } |
|
1032 |
#' |
|
1033 |
#' @note For `diagnose_pagination`, the column labels are not |
|
1034 |
#' displayed in the `col_diagnostics` element due to certain |
|
1035 |
#' internal implementation details; rather the diagnostics are |
|
1036 |
#' reported in terms of absolute (leaf) column position. This is a |
|
1037 |
#' known limitation, and may eventually be changed, but the |
|
1038 |
#' information remains useful as it is currently reported. |
|
1039 |
#' |
|
1040 |
#' @note `diagnose_pagination` is intended for interactive debugging |
|
1041 |
#' use and \emph{should not be programmed against}, as the exact |
|
1042 |
#' content and form of the verbose messages it captures and |
|
1043 |
#' returns is subject to change. |
|
1044 |
#' |
|
1045 |
#' @note because `diagnose_pagination` relies on `capture.output(type = "message")`, |
|
1046 |
#' it cannot be used within the `testthat` (and likely other) testing frameworks, |
|
1047 |
#' and likely cannot be used within `knitr`/`rmarkdown` contexts either, |
|
1048 |
#' as this clashes with those systems' capture of messages. |
|
1049 |
#' |
|
1050 |
#' @export |
|
1051 |
#' |
|
1052 |
#' @rdname paginate_indices |
|
1053 |
#' @examples |
|
1054 |
#' |
|
1055 |
#' diagnose_pagination(mpf, pg_width = 5, pg_height = 3) |
|
1056 |
#' clws <- propose_column_widths(mpf) |
|
1057 |
#' clws[1] <- floor(clws[1]/3) |
|
1058 |
#' dgnost <- diagnose_pagination(mpf, pg_width = 5, pg_height = 3, colwidths = clws) |
|
1059 |
#' try(diagnose_pagination(mpf, pg_width = 1)) #fails |
|
1060 |
#' |
|
1061 |
diagnose_pagination <- function(obj, |
|
1062 |
page_type = "letter", |
|
1063 |
font_family = "Courier", |
|
1064 |
font_size = 8, |
|
1065 |
lineheight = 1, |
|
1066 |
landscape = FALSE, |
|
1067 |
pg_width = NULL, |
|
1068 |
pg_height = NULL, |
|
1069 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
1070 |
lpp = NA_integer_, |
|
1071 |
cpp = NA_integer_, |
|
1072 |
min_siblings = 2, |
|
1073 |
nosplitin = character(), |
|
1074 |
colwidths = propose_column_widths(matrix_form(obj, TRUE)), |
|
1075 |
tf_wrap = FALSE, |
|
1076 |
max_width = NULL, |
|
1077 |
indent_size = 2, |
|
1078 |
pg_size_spec = NULL, |
|
1079 |
rep_cols = num_rep_cols(obj), |
|
1080 |
col_gap = 2, |
|
1081 |
verbose = FALSE, |
|
1082 |
...) { |
|
1083 | ||
1084 | ||
1085 | 6x |
fpag <- do_forced_paginate(obj) |
1086 | 6x |
if(length(fpag) > 1) { |
1087 | 1x |
return(lapply(fpag, |
1088 | 1x |
diagnose_pagination, |
1089 | 1x |
page_type = page_type, |
1090 | 1x |
font_family = font_family, |
1091 | 1x |
font_size = font_size, |
1092 | 1x |
lineheight = lineheight, |
1093 | 1x |
landscape = landscape, |
1094 | 1x |
pg_width = pg_width, |
1095 | 1x |
pg_height = pg_height, |
1096 | 1x |
margins = margins, |
1097 | 1x |
lpp = lpp, |
1098 | 1x |
cpp = cpp, |
1099 | 1x |
tf_wrap = tf_wrap, |
1100 | 1x |
max_width = max_width, |
1101 | 1x |
colwidths = colwidths, |
1102 | 1x |
col_gap = col_gap, |
1103 | 1x |
min_siblings = min_siblings, |
1104 | 1x |
nosplitin = nosplitin)) |
1105 |
} |
|
1106 | ||
1107 | 5x |
mpf <- matrix_form(obj, TRUE) |
1108 | 5x |
msgres <- capture.output({tmp <- try(paginate_to_mpfs(obj, page_type = page_type, |
1109 | 5x |
font_family = font_family, |
1110 | 5x |
font_size = font_size, |
1111 | 5x |
lineheight = lineheight, |
1112 | 5x |
landscape = landscape, |
1113 | 5x |
pg_width = pg_width, |
1114 | 5x |
pg_height = pg_height, |
1115 | 5x |
margins = margins, |
1116 | 5x |
lpp = lpp, |
1117 | 5x |
cpp = cpp, |
1118 | 5x |
tf_wrap = tf_wrap, |
1119 | 5x |
max_width = max_width, |
1120 | 5x |
colwidths = colwidths, |
1121 | 5x |
col_gap = col_gap, |
1122 | 5x |
min_siblings = min_siblings, |
1123 | 5x |
nosplitin = nosplitin, |
1124 | 5x |
verbose = TRUE))}, |
1125 | 5x |
type = "message") |
1126 | 5x |
if(is(tmp, "try-error") && grepl("Width of row labels equal to or larger", tmp)) { |
1127 | ! |
cond <- attr(tmp, "condition") |
1128 | ! |
stop(conditionMessage(cond), call. = conditionCall(cond)) |
1129 |
} |
|
1130 | ||
1131 | 5x |
lpp_diagnostic <- grep("^(Determining lines|Lines per page available).*$", msgres, value = TRUE) |
1132 | 5x |
cpp_diagnostic <- unique(grep("^Adjusted characters per page.*$", msgres, value = TRUE)) |
1133 | ||
1134 | 5x |
mpf <- do_cell_fnotes_wrap(mpf, widths = colwidths, max_width = max_width, tf_wrap = tf_wrap) |
1135 | 5x |
mpf <- mpf_infer_cinfo(mpf, colwidths = colwidths) |
1136 | ||
1137 | 5x |
rownls <- grep("Checking pagination after row", msgres, fixed = TRUE) |
1138 | 5x |
rownum <- as.integer(gsub("[^[:digit:]]*(.*)$", "\\1", msgres[rownls])) |
1139 | 5x |
rowmsgs <- vapply(unique(rownum), function(ii) { |
1140 | ! |
idx <- max(which(rownum == ii)) |
1141 | ! |
gsub("\\t[.]*", "", msgres[rownls[idx] + 1]) |
1142 |
}, "") |
|
1143 | ||
1144 | 5x |
msgdf <- data.frame(abs_rownumber = unique(rownum), |
1145 | 5x |
final_pag_result = rowmsgs, stringsAsFactors = FALSE) |
1146 | 5x |
rdf <-mf_rinfo(mpf)[, c("abs_rownumber", "label", "self_extent", "par_extent", "node_class")] |
1147 | 5x |
rdf$pag_attempted <- rdf$abs_rownumber %in% rownum |
1148 | 5x |
row_diagnose <- merge(rdf, msgdf, by = "abs_rownumber", all.x = TRUE) |
1149 | ||
1150 | 5x |
colnls <- grep("Checking pagination after column", msgres, fixed = TRUE) |
1151 | 5x |
colnum <- as.integer(gsub("[^[:digit:]]*(.*)$", "\\1", msgres[colnls])) |
1152 | 5x |
colmsgs <- vapply(unique(colnum), function(ii) { |
1153 | ! |
idx <- max(which(colnum == ii)) |
1154 | ! |
gsub("\\t[.]*", "", msgres[colnls[idx] + 1]) |
1155 |
}, "") |
|
1156 | ||
1157 | 5x |
colmsgdf <- data.frame(abs_rownumber = unique(colnum), |
1158 | 5x |
final_pag_result = colmsgs, |
1159 | 5x |
stringsAsFactors = FALSE) |
1160 | 5x |
cdf <- mf_cinfo(mpf)[, c("abs_rownumber", "self_extent")] |
1161 | 5x |
cdf$pag_attempted <- cdf$abs_rownumber %in% colnum |
1162 | 5x |
col_diagnose <- merge(cdf, colmsgdf, by = "abs_rownumber", all.x = TRUE) |
1163 | 5x |
names(col_diagnose) <- gsub("^abs_rownumber$", "abs_colnumber", names(col_diagnose)) |
1164 | 5x |
list(lpp_diagnostics = lpp_diagnostic, |
1165 | 5x |
row_diagnostics = row_diagnose, |
1166 | 5x |
cpp_diagnostics = cpp_diagnostic, |
1167 | 5x |
col_diagnostics = col_diagnose) |
1168 |
} |
1 |
## until we do it for real |
|
2 | ||
3 |
#' @title Matrix Print Form - Intermediate Representation for ASCII Table Printing |
|
4 |
#' |
|
5 |
#' @name MatrixPrintForm-class |
|
6 |
#' |
|
7 |
#' @rdname MatrixPrintForm_class |
|
8 |
#' @aliases MatrixPrintForm-class |
|
9 |
#' @exportClass MatrixPrintForm |
|
10 |
setOldClass(c("MatrixPrintForm", "list")) |
|
11 | ||
12 | ||
13 |
mform_handle_newlines <- function(matform) { |
|
14 |
# Retrieving relevant information |
|
15 | 112x |
has_topleft <- mf_has_topleft(matform) |
16 | 112x |
strmat <- mf_strings(matform) |
17 | 112x |
frmmat <- mf_formats(matform) |
18 |
# nlines detects if there is a newline character |
|
19 | 112x |
row_nlines <- apply(strmat, 1, function(x) max(vapply(x, nlines, 1L), 1L)) |
20 | 112x |
nr_header <- mf_nrheader(matform) |
21 | ||
22 |
# There is something to change |
|
23 | 112x |
if (any(row_nlines > 1)) { |
24 |
# Header indices |
|
25 | 4x |
hdr_inds <- 1:nr_header |
26 |
## groundwork for sad haxx to get tl to not be messed up |
|
27 | 4x |
if (has_topleft) { |
28 | 2x |
tl <- strmat[hdr_inds, 1] |
29 | 2x |
strmat[hdr_inds, 1] <- "" |
30 |
## recalc them without topleft cause thats handled separately |
|
31 | 2x |
row_nlines <- apply(strmat, 1, function(x) max(vapply(x, nlines, 1L), 1L)) |
32 |
} else { |
|
33 | 2x |
tl <- character() |
34 |
} |
|
35 |
## used below even though we don't store it on the resulting object |
|
36 | 4x |
new_nlines_hdr <- sum(row_nlines[hdr_inds]) |
37 | 4x |
newstrmat <- rbind( |
38 | 4x |
expand_mat_rows(strmat[hdr_inds, , drop = FALSE], |
39 | 4x |
row_nlines[hdr_inds], |
40 | 4x |
cpadder = pad_vert_bottom |
41 |
), |
|
42 | 4x |
expand_mat_rows(strmat[-1 * hdr_inds, , drop = FALSE], row_nlines[-hdr_inds]) |
43 |
) |
|
44 | 4x |
newfrmmat <- rbind( |
45 | 4x |
expand_mat_rows(frmmat[hdr_inds, , drop = FALSE], |
46 | 4x |
row_nlines[hdr_inds], |
47 | 4x |
cpadder = pad_vert_bottom |
48 |
), |
|
49 | 4x |
expand_mat_rows(frmmat[-1 * hdr_inds, , drop = FALSE], row_nlines[-hdr_inds]) |
50 |
) |
|
51 |
## sad haxx :( |
|
52 | 4x |
if (has_topleft) { |
53 | 2x |
newtl <- unlist(strsplit(tl, "\n")) |
54 | 2x |
if (length(newtl) > new_nlines_hdr) { |
55 |
stop("Expanding top-left material resulted in more lines (", length(newtl), # nocov |
|
56 |
"than fit in the header.") # nocov |
|
57 |
} |
|
58 | 1x |
newstrmat[1:new_nlines_hdr, 1] <- c(newtl, rep("", new_nlines_hdr - length(newtl))) |
59 | 1x |
newfrmmat[1:new_nlines_hdr, 1] <- "xx" |
60 |
} |
|
61 | 3x |
mf_strings(matform) <- newstrmat |
62 | 3x |
mf_formats(matform) <- newfrmmat |
63 | 3x |
mf_spans(matform) <- expand_mat_rows(mf_spans(matform), row_nlines, rep_vec_to_len) |
64 | 3x |
mf_aligns(matform) <- expand_mat_rows(mf_aligns(matform), row_nlines, rep_vec_to_len) |
65 |
## mf_display(matform) <- expand_mat_rows(mf_display(matform), row_nlines, rep_vec_to_len) |
|
66 | 3x |
mf_lgrouping(matform) <- rep(mf_lgrouping(matform), times = row_nlines) |
67 |
} |
|
68 | ||
69 | 111x |
matform |
70 |
} |
|
71 | ||
72 |
disp_from_spans <- function(spans) { |
|
73 | ||
74 | 139x |
display <- matrix(rep(TRUE, length(spans)), ncol = ncol(spans)) |
75 | ||
76 | 139x |
print_cells_mat <- spans == 1L |
77 | 139x |
if (!all(print_cells_mat)) { |
78 | 1x |
display_rws <- lapply( |
79 | 1x |
seq_len(nrow(spans)), |
80 | 1x |
function(i) { |
81 | 2x |
print_cells <- print_cells_mat[i, ] |
82 | 2x |
row <- spans[i, ] |
83 |
## display <- t(apply(spans, 1, function(row) { |
|
84 |
## print_cells <- row == 1 |
|
85 | ||
86 | 2x |
if (!all(print_cells)) { |
87 |
## need to calculate which cell need to be printed |
|
88 | 1x |
print_cells <- spans_to_viscell(row) |
89 |
} |
|
90 | 2x |
print_cells |
91 |
} |
|
92 |
) |
|
93 | 1x |
display <- do.call(rbind, display_rws) |
94 |
} |
|
95 | 139x |
display |
96 |
} |
|
97 | ||
98 |
## constructor |
|
99 |
#' @title Matrix Print Form - Intermediate Representation for ASCII Table Printing |
|
100 |
#' |
|
101 |
#' @note The bare constructor for the `MatrixPrintForm` should generally |
|
102 |
#' only be called by `matrix_form` custom methods, and almost never from other code. |
|
103 |
#' |
|
104 |
#' @param strings character matrix. Matrix of formatted, ready to |
|
105 |
#' display strings organized as they will be positioned when |
|
106 |
#' rendered. Elements that span more than one column must be |
|
107 |
#' followed by the correct number of placeholders (typically |
|
108 |
#' either empty strings or repeats of the value). |
|
109 |
#' @param spans numeric matrix. Matrix of same dimension as |
|
110 |
#' \code{strings} giving the spanning information for each |
|
111 |
#' element. Must be repeated to match placeholders in |
|
112 |
#' \code{strings}. |
|
113 |
#' @param aligns character matrix. Matrix of same dimension as |
|
114 |
#' \code{strings} giving the text alignment information for each |
|
115 |
#' element. Must be repeated to match placeholders in |
|
116 |
#' \code{strings}. Must be a supported text alignment. See |
|
117 |
#' [decimal_align] allowed values. |
|
118 |
#' @param formats matrix. Matrix of same dimension |
|
119 |
#' as \code{strings} giving the text format information for |
|
120 |
#' each element. Must be repeated to match placeholders in |
|
121 |
#' \code{strings}. |
|
122 |
#' @param row_info data.frame. Data.frame with row-information |
|
123 |
#' necessary for pagination (XXX document exactly what that is). |
|
124 |
#' @param line_grouping integer. Sequence of integers indicating how |
|
125 |
#' print lines correspond to semantic rows in the object. |
|
126 |
#' Typically this should not be set manually unless |
|
127 |
#' `expact_newlines` is set to \code{FALSE}. |
|
128 |
#' @param ref_fnotes list. Referential footnote information if |
|
129 |
#' applicable. |
|
130 |
#' @param nlines_header numeric(1). Number of lines taken up by the |
|
131 |
#' values of the header (i.e. not including the divider). |
|
132 |
#' @param nrow_header numeric(1). Number of \emph{rows} corresponding |
|
133 |
#' to the header. |
|
134 |
#' @param has_topleft logical(1). Does the corresponding table have |
|
135 |
#' 'top left information' which should be treated differently when |
|
136 |
#' expanding newlines. Ignored if \code{expand_newlines} is |
|
137 |
#' \code{FALSE}. |
|
138 |
#' @param has_rowlabs logical(1). Do the matrices (\code{strings}, |
|
139 |
#' \code{spans}, \code{aligns}) each contain a column that |
|
140 |
#' corresponds with row labels (Rather than with table cell |
|
141 |
#' values). Defaults to \code{TRUE}. |
|
142 |
#' @param main_title character(1). Main title as a string. |
|
143 |
#' @param subtitles character. Subtitles, as a character vector. |
|
144 |
#' @param page_titles character. Page-specific titles, as a character |
|
145 |
#' vector. |
|
146 |
#' @param main_footer character(1). Main footer as a string. |
|
147 |
#' @param prov_footer character. Provenance footer information as a |
|
148 |
#' character vector. |
|
149 |
#' @param expand_newlines logical(1). Should the matrix form generated |
|
150 |
#' expand rows whose values contain newlines into multiple |
|
151 |
#' 'physical' rows (as they will appear when rendered into |
|
152 |
#' ASCII). Defaults to \code{TRUE} |
|
153 |
#' @param col_gap numeric(1). Space (in characters) between columns |
|
154 |
#' @param table_inset numeric(1). Table inset. See |
|
155 |
#' \code{\link{table_inset}} |
|
156 |
#' @param colwidths numeric. NULL, or a vector of column rendering widths. |
|
157 |
#' if non-NULL, must have length equal to `ncol(strings)` |
|
158 |
#' @param indent_size numeric(1). Number of spaces to be used per level of indent (if supported by |
|
159 |
#' the relevant method). Defaults to 2. |
|
160 |
#' @export |
|
161 |
#' @return An object of class `MatrixPrintForm`. Currently this is |
|
162 |
#' implemented as an S3 class inheriting from list with the following |
|
163 |
#' elements: |
|
164 |
#' \describe{ |
|
165 |
#' \item{\code{strings}}{see argument} |
|
166 |
#' \item{\code{spans}}{see argument} |
|
167 |
#' \item{\code{aligns}}{see argument} |
|
168 |
#' \item{\code{display}}{logical matrix of same dimension as `strings` |
|
169 |
#' that specifies whether an element in `strings` will be displayed |
|
170 |
#' when the table is rendered} |
|
171 |
#' \item{\code{formats}}{see argument} |
|
172 |
#' \item{\code{row_info}}{see argument} |
|
173 |
#' \item{\code{line_grouping}}{see argument} |
|
174 |
#' \item{\code{ref_footnotes}}{see argument} |
|
175 |
#' \item{\code{main_title}}{see argument} |
|
176 |
#' \item{\code{subtitles}}{see argument} |
|
177 |
#' \item{\code{page_titles}}{see argument} |
|
178 |
#' \item{\code{main_footer}}{see argument} |
|
179 |
#' \item{\code{prov_footer}}{see argument} |
|
180 |
#' \item{\code{col_gap}}{see argument} |
|
181 |
#' \item{\code{table_inset}}{see argument} |
|
182 |
#' } |
|
183 |
#' |
|
184 |
#' as well as the following attributes: |
|
185 |
#' \describe{ |
|
186 |
#' \item{\code{nlines_header}}{see argument} |
|
187 |
#' \item{\code{nrow_header}}{see argument} |
|
188 |
#' \item{\code{ncols}}{number of columns \emph{of the table}, not including |
|
189 |
#' any row names/row labels} |
|
190 |
#' } |
|
191 |
MatrixPrintForm <- function(strings = NULL, |
|
192 |
spans, |
|
193 |
aligns, |
|
194 |
formats, |
|
195 |
row_info, |
|
196 |
line_grouping = seq_len(NROW(strings)), |
|
197 |
ref_fnotes = list(), |
|
198 |
nlines_header, |
|
199 |
nrow_header, |
|
200 |
has_topleft = TRUE, |
|
201 |
has_rowlabs = has_topleft, |
|
202 |
expand_newlines = TRUE, |
|
203 |
main_title = "", |
|
204 |
subtitles = character(), |
|
205 |
page_titles = character(), |
|
206 |
main_footer = "", |
|
207 |
prov_footer = character(), |
|
208 |
col_gap = 3, |
|
209 |
table_inset = 0L, |
|
210 |
colwidths = NULL, |
|
211 |
indent_size = 2) { |
|
212 | 27x |
display <- disp_from_spans(spans) |
213 | ||
214 | ||
215 | 27x |
ncs <- if (has_rowlabs) ncol(strings) - 1 else ncol(strings) |
216 | 27x |
ret <- structure( |
217 | 27x |
list( |
218 | 27x |
strings = strings, |
219 | 27x |
spans = spans, |
220 | 27x |
aligns = aligns, |
221 | 27x |
display = display, |
222 | 27x |
formats = formats, |
223 | 27x |
row_info = row_info, |
224 | 27x |
line_grouping = line_grouping, |
225 | 27x |
ref_footnotes = ref_fnotes, |
226 | 27x |
main_title = main_title, |
227 | 27x |
subtitles = subtitles, |
228 | 27x |
page_titles = page_titles, |
229 | 27x |
main_footer = main_footer, |
230 | 27x |
prov_footer = prov_footer, |
231 | 27x |
col_gap = col_gap, |
232 | 27x |
table_inset = as.integer(table_inset), |
233 | 27x |
has_topleft = has_topleft, |
234 | 27x |
indent_size = indent_size, |
235 | 27x |
col_widths = colwidths |
236 |
), |
|
237 | 27x |
nrow_header = nrow_header, |
238 | 27x |
ncols = ncs, |
239 | 27x |
class = c("MatrixPrintForm", "list") |
240 |
) |
|
241 | ||
242 | ||
243 |
## .do_mat_expand(ret) |
|
244 | 27x |
if (expand_newlines) { |
245 | 27x |
ret <- mform_handle_newlines(ret) |
246 |
} |
|
247 | ||
248 | ||
249 |
## ret <- shove_refdf_into_rowinfo(ret) |
|
250 | 27x |
if(is.null(colwidths)) |
251 | 27x |
colwidths <- propose_column_widths(ret) |
252 | 27x |
mf_col_widths(ret) <- colwidths |
253 | 27x |
ret <- mform_build_refdf(ret) |
254 | 27x |
ret |
255 |
} |
|
256 | ||
257 | ||
258 |
#'Create a row for a referential footnote information dataframe |
|
259 |
#' |
|
260 |
#' @inheritParams nlines |
|
261 |
#' @param row_path character. row path (`NA_character_` for none) |
|
262 |
#' @param col_path character. column path (`NA_character_` for none) |
|
263 |
#' @param row integer(1). Integer position of the row. |
|
264 |
#' @param col integer(1). Integer position of the column. |
|
265 |
#' @param symbol character(1). Symbol for the reference. `NA_character_` to use the `ref_index` automatically. |
|
266 |
#' @param ref_index integer(1). The index of the footnote, used for ordering even when symbol is not NA |
|
267 |
#' @param msg character(1). The string message, not including the symbol portion (`{symbol} - `) |
|
268 |
#' |
|
269 |
#' @return a single row data.frame with the appropriate columns. |
|
270 |
#' |
|
271 |
#' @export |
|
272 |
#' |
|
273 |
ref_df_row <- function(row_path = NA_character_, col_path = NA_character_, row = NA_integer_, col = NA_integer_, symbol = NA_character_, ref_index = NA_integer_, msg = NA_character_, max_width = NULL) { |
|
274 | 3390x |
nlines <- nlines(msg, max_width = max_width) |
275 | 3390x |
data.frame(row_path = I(list(row_path)), |
276 | 3390x |
col_path = I(list(col_path)), |
277 | 3390x |
row = row, |
278 | 3390x |
col = col, |
279 | 3390x |
symbol = symbol, |
280 | 3390x |
ref_index = ref_index, |
281 | 3390x |
msg = msg, |
282 | 3390x |
nlines = nlines, |
283 | 3390x |
stringsAsFactors = FALSE) |
284 |
} |
|
285 | ||
286 | ||
287 |
## this entire thing is a hatchetjob of a hack which should not be necessary. |
|
288 |
## mf_rinfo(mform) should have the relevant info in it and |
|
289 |
## mf_cinfo(mform) should be non-null (!!!) and have the info in it |
|
290 |
## in which case this becomes silly and dumb, but here we are, so here we go. |
|
291 |
infer_ref_info <- function(mform, colspace_only) { |
|
292 | 108x |
if(colspace_only) |
293 | 54x |
idx <- seq_len(mf_nlheader(mform)) |
294 |
else |
|
295 | 54x |
idx <- seq_len(nrow(mf_strings(mform))) |
296 | ||
297 | ||
298 | 108x |
hasrlbs <- mf_has_rlabels(mform) |
299 | ||
300 | 108x |
strs <- mf_strings(mform)[idx, , drop = FALSE] |
301 | ||
302 |
## they're nested so \\2 is the inner one, without the brackets |
|
303 | 108x |
refs <- gsub("^[^{]*([{]([^}]+)[}]){0,1}$", "\\2", strs) |
304 |
## handle spanned values |
|
305 | 108x |
refs[!mf_display(mform)[idx,]] <- "" |
306 | ||
307 |
## we want to count across rows first, not down columns, cause |
|
308 |
## thats how footnote numbering works |
|
309 | 108x |
refs_inorder <- as.vector(t(refs)) |
310 | 108x |
keepem <- nzchar(refs_inorder) |
311 | 108x |
if(sum(keepem) == 0) |
312 | 106x |
return(ref_df_row()[0,]) |
313 | ||
314 | 2x |
refs_spl <- strsplit(refs_inorder[keepem], ", ", fixed = TRUE) |
315 | 2x |
runvec <- vapply(refs_spl, length, 1L) |
316 | ||
317 | ||
318 | ||
319 | 2x |
row_index <- as.vector(t(do.call(cbind, replicate(ncol(strs), |
320 | 2x |
list(mf_lgrouping(mform)[idx] - mf_nlheader(mform))))))[keepem] |
321 | 2x |
row_index[row_index < 1] <- NA_integer_ |
322 | 2x |
c_torep <- if(hasrlbs) c(NA_integer_, seq(1, ncol(strs) - 1)) else seq_len(ncol(strs)) |
323 | 2x |
col_index <- rep(c_torep, nrow(strs))[keepem] |
324 | ||
325 | ||
326 | ||
327 | ||
328 | 2x |
ret <- data.frame(symbol = unlist(refs_spl), |
329 | 2x |
row_path = I(mf_rinfo(mform)$path[rep(row_index, times = runvec)]), |
330 | 2x |
row = rep(row_index, times = runvec), |
331 | 2x |
col = rep(col_index, times = runvec)) |
332 | 2x |
ret$msg <- vapply(ret$symbol, function(sym) { |
333 | 16x |
fullmsg <- unique(grep(paste0("{",sym, "}"), fixed = TRUE, mf_rfnotes(mform), value = TRUE)) |
334 | 16x |
gsub("^[{][^}]+[}] - ", "", fullmsg) |
335 |
}, "") |
|
336 | ||
337 | ||
338 | 2x |
col_pths <- mf_col_paths(mform) |
339 | 2x |
ret$col_path <- replicate(nrow(ret), list(NA_character_)) |
340 | 2x |
non_na_col <- !is.na(ret$col) |
341 | 2x |
ret$col_path[non_na_col] <- col_pths[ret$col[non_na_col]] |
342 | 2x |
ret$ref_index <- seq_len(nrow(ret)) |
343 |
## |
|
344 | 2x |
ret$nlines <- vapply(paste0("{", ret$symbol, "} - ", ret$msg), nlines, 1L) |
345 | 2x |
ret <- ret[,names(ref_df_row())] |
346 | 2x |
ret |
347 |
} |
|
348 | ||
349 |
mform_build_refdf <- function(mform) { |
|
350 | 54x |
rdf <- mf_rinfo(mform) |
351 | 54x |
cref_rows <- infer_ref_info(mform, colspace_only = TRUE) |
352 |
## this will recheck sometimes but its safer and shouldn't |
|
353 |
## be too prohibitively costly |
|
354 | 54x |
if(NROW(rdf$ref_info_df) > 0 && sum(sapply(rdf$ref_info_df, NROW)) > 0) { |
355 | ! |
cref_rows <- infer_ref_info(mform, colspace_only = TRUE) |
356 | ! |
rref_rows <- rdf$ref_info_df |
357 |
} else { |
|
358 | 54x |
cref_rows <- infer_ref_info(mform, colspace_only = FALSE) |
359 | 54x |
rref_rows <- list() |
360 |
} |
|
361 | 54x |
mf_fnote_df(mform) <- do.call(rbind.data.frame, c(list(cref_rows), rref_rows)) |
362 | 54x |
update_mf_nlines(mform, colwidths = mf_col_widths(mform), max_width = NULL) |
363 |
} |
|
364 | ||
365 | ||
366 | ||
367 | ||
368 | ||
369 | ||
370 | ||
371 | ||
372 | ||
373 |
## constructor with snake_case naming convention |
|
374 |
#' @rdname MatrixPrintForm |
|
375 |
#' @export |
|
376 |
matrix_print_form <- MatrixPrintForm |
|
377 | ||
378 | ||
379 |
## hide the implementation behind abstraction in case we decide we want a real class someday |
|
380 |
#' `Setters` and `getters` for aspects of `MatrixPrintForm` Objects |
|
381 |
#' |
|
382 |
#' Most of these functions, particularly the `settters`, are intended |
|
383 |
#' almost exclusively for internal use in, e.g., `matrix_form` methods, |
|
384 |
#' and should generally not be called by end users. |
|
385 |
#' |
|
386 |
#' @param mf `MatrixPrintForm(1)`. A `MatrixPrintForm` object |
|
387 |
#' @param value ANY. The new value for the component in question. |
|
388 |
#' @return The element of the `MatrixPrintForm` associated with the `getter`, or |
|
389 |
#' the modified `MatrixPrintForm` object in the case of a `setter`. |
|
390 |
#' @export |
|
391 |
#' @rdname mpf_accessors |
|
392 | 1362x |
mf_strings <- function(mf) mf$strings |
393 | ||
394 |
#' @export |
|
395 |
#' @rdname mpf_accessors |
|
396 | ||
397 | 180x |
mf_spans <- function(mf) mf$spans |
398 |
#' @export |
|
399 |
#' @rdname mpf_accessors |
|
400 | ||
401 | 314x |
mf_aligns <- function(mf) mf$aligns |
402 | ||
403 |
#' @export |
|
404 |
#' @rdname mpf_accessors |
|
405 | 233x |
mf_display <- function(mf) mf$display |
406 | ||
407 |
#' @export |
|
408 |
#' @rdname mpf_accessors |
|
409 | 221x |
mf_formats <- function(mf) mf$formats |
410 | ||
411 |
#' @export |
|
412 |
#' @rdname mpf_accessors |
|
413 | 569x |
mf_rinfo <- function(mf) mf$row_info |
414 | ||
415 |
#' @export |
|
416 |
#' @rdname mpf_accessors |
|
417 | 78x |
mf_cinfo <- function(mf) mf$col_info |
418 | ||
419 | ||
420 |
#' @export |
|
421 |
#' @rdname mpf_accessors |
|
422 | 197x |
mf_has_topleft <- function(mf) mf$has_topleft |
423 | ||
424 |
#' @export |
|
425 |
#' @rdname mpf_accessors |
|
426 | 1635x |
mf_lgrouping <- function(mf) mf$line_grouping |
427 | ||
428 |
#' @export |
|
429 |
#' @rdname mpf_accessors |
|
430 | 75x |
mf_rfnotes <- function(mf) mf$ref_footnotes |
431 | ||
432 |
#' @export |
|
433 |
#' @rdname mpf_accessors |
|
434 | 685x |
mf_nlheader <- function(mf) sum(mf_lgrouping(mf) <= mf_nrheader(mf)) |
435 | ||
436 |
#' @export |
|
437 |
#' @rdname mpf_accessors |
|
438 | 1003x |
mf_nrheader <- function(mf) attr(mf, "nrow_header", exact = TRUE) |
439 | ||
440 | ||
441 |
#' @export |
|
442 |
#' @rdname mpf_accessors |
|
443 | 143x |
mf_colgap <- function(mf) mf$col_gap |
444 | ||
445 | ||
446 | ||
447 | ||
448 |
## XXX should this be exported? not sure if there's a point |
|
449 |
mf_col_paths <- function(mf) { |
|
450 | 2x |
if(!is.null(mf_cinfo(mf))) |
451 | ! |
mf_cinfo(mf)$path |
452 |
else |
|
453 | 2x |
as.list(paste0("col", seq_len(nrow(mf_strings(mf)) - mf_has_topleft(mf)))) |
454 |
} |
|
455 | ||
456 | ||
457 |
mf_col_widths <- function(mf) { |
|
458 | 200x |
mf$col_widths |
459 |
} |
|
460 | ||
461 |
`mf_col_widths<-` <- function(mf, value) { |
|
462 | 153x |
if(!is.null(value) && length(value) != NCOL(mf_strings(mf))) |
463 | ! |
stop("Number of column widths (", length(value), ") does not match ", |
464 | ! |
"number of columns in strings matrix (", NCOL(mf_strings(mf)), ").") |
465 | 153x |
mf$col_widths <- value |
466 | 153x |
mf |
467 |
} |
|
468 | ||
469 |
mf_fnote_df <- function(mf) { |
|
470 | 695x |
mf$ref_fnote_df |
471 |
} |
|
472 | ||
473 |
`mf_fnote_df<-` <- function(mf, value) { |
|
474 | 190x |
stopifnot(is.null(value) || ( |
475 | 190x |
is.data.frame(value) && identical(names(value), names(ref_df_row())))) |
476 | 190x |
mf$ref_fnote_df <- value |
477 | 190x |
mf |
478 |
} |
|
479 | ||
480 | ||
481 |
splice_fnote_info_in <- function(df, refdf, row = TRUE) { |
|
482 | 182x |
if(NROW(df) == 0) |
483 | ! |
return(df) |
484 | ||
485 | 182x |
colnm <- ifelse(row, "row", "col") |
486 | 182x |
refdf <- refdf[!is.na(refdf[[colnm]]),] |
487 | ||
488 | 182x |
refdf_spl <- split(refdf, refdf[[colnm]]) |
489 | 182x |
df$ref_info_df <- replicate(nrow(df), list(ref_df_row()[0,])) |
490 | 182x |
df$ref_info_df[as.integer(names(refdf_spl))] <- refdf_spl |
491 | 182x |
df |
492 |
} |
|
493 | ||
494 | ||
495 |
shove_refdf_into_rowinfo <- function(mform) { |
|
496 | 136x |
refdf <- mf_fnote_df(mform) |
497 | 136x |
rowinfo <- mf_rinfo(mform) |
498 | 136x |
mf_rinfo(mform) <- splice_fnote_info_in(rowinfo, refdf) |
499 | 136x |
mform |
500 |
} |
|
501 | ||
502 |
update_mf_nlines <- function(mform, colwidths, max_width) { |
|
503 | 137x |
mform <- update_mf_ref_nlines(mform, max_width = max_width) |
504 | 137x |
mform <- update_mf_rinfo_extents(mform) |
505 | ||
506 | 137x |
mform |
507 |
} |
|
508 | ||
509 |
update_mf_rinfo_extents <- function(mform) { |
|
510 | 137x |
rinfo <- mf_rinfo(mform) |
511 | 137x |
refdf_all <- mf_fnote_df(mform) |
512 | 137x |
refdf_rows <- refdf_all[!is.na(refdf_all$row),] |
513 | 137x |
if(NROW(rinfo) == 0) |
514 | ! |
return(mform) |
515 | 137x |
lgrp <- mf_lgrouping(mform) - mf_nrheader(mform) |
516 | 137x |
lgrp <- lgrp[lgrp > 0] |
517 | 137x |
rf_nlines <- vapply(seq_len(max(lgrp)), function(ii) { |
518 | ||
519 | 2920x |
refdfii <- refdf_rows[refdf_rows$row == ii,] |
520 | 2920x |
refdfii <- refdfii[!duplicated(refdfii$symbol), ] |
521 | 2920x |
if(NROW(refdfii) == 0L) |
522 | 2824x |
return(0L) |
523 | 96x |
sum(refdfii$nlines) |
524 | 137x |
}, 1L) |
525 | ||
526 | 137x |
raw_self_exts <- vapply(split(lgrp, lgrp), length, 0L) |
527 | 137x |
stopifnot(length(raw_self_exts) == length(rf_nlines)) |
528 | 137x |
new_exts <- raw_self_exts + rf_nlines |
529 | ||
530 | 137x |
mapdf <- data.frame(row_num = as.integer(names(new_exts)), |
531 | 137x |
raw_extent = raw_self_exts) |
532 | 137x |
stopifnot(all(mapdf$row_num == rinfo$abs_rownumber)) |
533 | ||
534 | ||
535 | 137x |
new_par_exts <- vapply(rinfo$reprint_inds, |
536 | 137x |
function(idx) { |
537 | 2920x |
sum(0L, mapdf$raw_extent[mapdf$row_num %in% idx]) |
538 | 137x |
}, 1L) |
539 | ||
540 | 137x |
rinfo$self_extent <- new_exts |
541 | 137x |
rinfo$par_extent <- new_par_exts |
542 | 137x |
rinfo$nreflines <- rf_nlines |
543 | 137x |
mf_rinfo(mform) <- rinfo |
544 | 137x |
mform |
545 |
} |
|
546 | ||
547 |
update_mf_ref_nlines <- function(mform, max_width) { |
|
548 | 137x |
refdf <- mf_fnote_df(mform) |
549 | 137x |
if(NROW(refdf) == 0) |
550 | 110x |
return(mform) |
551 | ||
552 | 27x |
refdf$nlines <- vapply(paste0("{", refdf$symbol, "} - ", refdf$msg), |
553 | 27x |
nlines, |
554 | 27x |
max_width = max_width, |
555 | 27x |
1L) |
556 | 27x |
mf_fnote_df(mform) <- refdf |
557 | 27x |
shove_refdf_into_rowinfo(mform) |
558 |
} |
|
559 | ||
560 | ||
561 | ||
562 |
#' @export |
|
563 |
#' @rdname mpf_accessors |
|
564 |
`mf_strings<-` <- function(mf, value) { |
|
565 | 198x |
mf$strings <- value |
566 | 198x |
mf |
567 |
} |
|
568 | ||
569 |
.chkdim_and_replace <- function(mf, value, component) { |
|
570 | 351x |
strdim <- dim(mf_strings(mf)) |
571 | 351x |
vdim <- dim(value) |
572 | 351x |
if (!is.null(strdim) && !identical(strdim, vdim)) { |
573 | 1x |
stop( |
574 | 1x |
"Dimensions of new '", component, "' value (", |
575 | 1x |
vdim[1], ", ", vdim[2], # nocov |
576 | 1x |
") do not match dimensions of existing 'strings' component (", # nocov |
577 | 1x |
strdim[1], ", ", strdim[2], ")." # nocov |
578 |
) |
|
579 |
} |
|
580 | 350x |
mf[[component]] <- value |
581 | 350x |
mf |
582 |
} |
|
583 | ||
584 | ||
585 |
#' @export |
|
586 |
#' @rdname mpf_accessors |
|
587 |
`mf_spans<-` <- function(mf, value) { |
|
588 | 113x |
mf <- .chkdim_and_replace(mf, value, component = "spans") |
589 | 112x |
mf$display <- disp_from_spans(value) |
590 | 112x |
mf |
591 |
} |
|
592 | ||
593 |
#' @export |
|
594 |
#' @rdname mpf_accessors |
|
595 |
`mf_aligns<-` <- function(mf, value) { |
|
596 | 126x |
.chkdim_and_replace(mf, value, component = "aligns") |
597 |
} |
|
598 | ||
599 | ||
600 |
#' @export |
|
601 |
#' @rdname mpf_accessors |
|
602 |
`mf_display<-` <- function(mf, value) { |
|
603 | ! |
stop("display is now a derived element of the matrix print form, modify it via `mf_spans<-`") |
604 | ! |
.chkdim_and_replace(mf, value, component = "display") |
605 |
} |
|
606 | ||
607 |
#' @export |
|
608 |
#' @rdname mpf_accessors |
|
609 |
`mf_formats<-` <- function(mf, value) { |
|
610 | 112x |
.chkdim_and_replace(mf, value, component = "formats") |
611 |
} |
|
612 | ||
613 | ||
614 |
## NB NROW(v) == length(v) for atomic vectors so this is ok for lgrouping as wellas rinfo |
|
615 |
.chknrow_and_replace <- function(mf, value, component, noheader = FALSE) { |
|
616 | 112x |
strdim <- NROW(mf_strings(mf)) - if (noheader) mf_nlheader(mf) else 0L |
617 | 112x |
vdim <- NROW(value) |
618 | 112x |
if (!is.null(strdim) && !identical(strdim, vdim)) { |
619 | ! |
stop( |
620 | ! |
"Number of rows/length of new '", component, "' value (", |
621 | ! |
vdim[1], |
622 | ! |
") does not match existing 'strings' component (", |
623 | ! |
strdim[1], ")." |
624 |
) |
|
625 |
} |
|
626 | 112x |
mf[[component]] <- value |
627 | 112x |
mf |
628 |
} |
|
629 | ||
630 |
#' @export |
|
631 |
#' @rdname mpf_accessors |
|
632 |
`mf_rinfo<-` <- function(mf, value) { |
|
633 |
## this can someijtmes be called after expanding newlines so in general |
|
634 |
## we should not expect it to match the number of rows in the strings matrix |
|
635 |
##.chknrow_and_replace(mf, value, component = "row_info", noheader = TRUE) |
|
636 | 319x |
lgrps <- mf_lgrouping(mf) |
637 | 319x |
nrs <- length(unique(lgrps[-seq_len(mf_nlheader(mf))])) |
638 | 319x |
if(NROW(value) != nrs) |
639 | 1x |
stop("Rows in new row_info component (", |
640 | 1x |
NROW(value), |
641 | 1x |
") does not match number of rows reflected in line_grouping component (", |
642 | 1x |
nrs, ")") |
643 | 318x |
mf$row_info <- value |
644 | 318x |
mf |
645 |
} |
|
646 | ||
647 |
#' @export |
|
648 |
#' @rdname mpf_accessors |
|
649 |
`mf_cinfo<-` <- function(mf, value) { |
|
650 | 46x |
if(NROW(value) > 0 && NROW(value) != ncol(mf)) |
651 | ! |
stop("Number of rows in new cinfo (", NROW(value), ") does not match ", |
652 | ! |
"number of columns (", ncol(mf), ")") |
653 | 46x |
mf$col_info <- value |
654 | 46x |
mf |
655 |
} |
|
656 | ||
657 | ||
658 |
#' @export |
|
659 |
#' @rdname mpf_accessors |
|
660 |
`mf_lgrouping<-` <- function(mf, value) { |
|
661 | 112x |
.chknrow_and_replace(mf, value, component = "line_grouping") |
662 |
} |
|
663 | ||
664 | ||
665 |
#' @export |
|
666 |
#' @rdname mpf_accessors |
|
667 |
`mf_rfnotes<-` <- function(mf, value) { |
|
668 | 114x |
mf$ref_footnotes <- value |
669 | 114x |
mf |
670 |
} |
|
671 | ||
672 | ||
673 | ||
674 |
#' @export |
|
675 |
#' @rdname mpf_accessors |
|
676 |
`mf_nrheader<-` <- function(mf, value) { |
|
677 | 2x |
attr(mf, "nrow_header") <- value |
678 | 2x |
mf |
679 |
} |
|
680 | ||
681 |
#' @export |
|
682 |
#' @rdname mpf_accessors |
|
683 |
`mf_colgap<-` <- function(mf, value) { |
|
684 | ! |
mf$col_gap <- value |
685 | ! |
mf |
686 |
} |
|
687 | ||
688 |
#' @export |
|
689 |
#' @rdname mpf_accessors |
|
690 | 475x |
mf_ncol <- function(mf) attr(mf, "ncols", exact = TRUE) |
691 | ||
692 |
#' @export |
|
693 |
#' @rdname mpf_accessors |
|
694 | 10x |
mf_nrow <- function(mf) max(mf_lgrouping(mf)) - mf_nrheader(mf) |
695 | ||
696 | ||
697 | ||
698 |
#' @export |
|
699 |
#' @rdname mpf_accessors |
|
700 |
`mf_ncol<-` <- function(mf, value) { |
|
701 | 136x |
stopifnot(is.numeric(value)) |
702 | 136x |
attr(mf, "ncols") <- value |
703 | 136x |
mf |
704 |
} |
|
705 | ||
706 |
#' @param x `MatrixPrintForm`. The object. |
|
707 |
#' @export |
|
708 |
#' @rdname mpf_accessors |
|
709 |
setMethod( |
|
710 |
"ncol", "MatrixPrintForm", |
|
711 | 474x |
function(x) mf_ncol(x) |
712 |
) |
|
713 | ||
714 |
#' @export |
|
715 |
#' @rdname mpf_accessors |
|
716 |
mpf_has_rlabels <- function(mf) { |
|
717 | ! |
.Deprecated("mf_has_rlabels") |
718 | ! |
mf_has_rlabels(mf) |
719 |
} |
|
720 | ||
721 |
#' @export |
|
722 |
#' @rdname mpf_accessors |
|
723 | 239x |
mf_has_rlabels <- function(mf) ncol(mf$strings) > ncol(mf) |
724 | ||
725 |
#' Create spoof matrix form from a data.frame |
|
726 |
#' |
|
727 |
#' This is useful primarily for writing testing/examples, and as a |
|
728 |
#' starting point for more sophisticated custom `matrix_form` methods |
|
729 |
#' |
|
730 |
#' @param df data.frame |
|
731 |
#' @param parent_path character. parent path that all rows should be "children of", |
|
732 |
#' defaults to `"root"`, and generally should not matter to end users. |
|
733 |
#' |
|
734 |
#' @return A valid `MatrixPrintForm` object representing `df`, |
|
735 |
#' ready for ASCII rendering |
|
736 |
#' |
|
737 |
#' @examples |
|
738 |
#' mform <- basic_matrix_form(mtcars) |
|
739 |
#' cat(toString(mform)) |
|
740 |
#' @export |
|
741 |
basic_matrix_form <- function(df, parent_path = "root") { |
|
742 | 25x |
fmts <- lapply(df, function(x) if (is.null(obj_format(x))) "xx" else obj_format(x)) |
743 | ||
744 | 25x |
bodystrs <- mapply(function(x, fmt) { |
745 | 127x |
sapply(x, format_value, format = fmt) |
746 | 25x |
}, x = df, fmt = fmts) |
747 | ||
748 | 25x |
rnms <- row.names(df) |
749 | 25x |
if (is.null(rnms)) { |
750 | ! |
rnms <- as.character(seq_len(NROW(df))) |
751 |
} |
|
752 | ||
753 | 25x |
cnms <- names(df) |
754 | ||
755 | 25x |
strings <- rbind( |
756 | 25x |
c("", cnms), |
757 | 25x |
cbind(rnms, bodystrs) |
758 |
) |
|
759 | ||
760 | 25x |
fnr <- nrow(strings) |
761 | 25x |
fnc <- ncol(strings) |
762 | ||
763 |
## center alignment for column labels, left alignment for everything else |
|
764 | 25x |
aligns <- rbind( |
765 | 25x |
"center", |
766 | 25x |
matrix("left", nrow = NROW(df), ncol = fnc) |
767 |
) |
|
768 | ||
769 | ||
770 |
## build up fake pagination df |
|
771 | 25x |
charcols <- which(sapply(df, is.character)) |
772 | 25x |
if (length(charcols) > 0) { |
773 | 1x |
exts <- apply(df[, charcols, drop = FALSE], 1, function(x) max(vapply(x, nlines, 1L))) |
774 |
} else { |
|
775 | 24x |
exts <- rep(1L, NROW(df)) |
776 |
} |
|
777 | 25x |
rowdf <- basic_pagdf(row.names(df), |
778 | 25x |
extents = exts, |
779 | 25x |
parent_path = parent_path |
780 |
) |
|
781 | 25x |
formats <- cbind( |
782 |
"", |
|
783 | 25x |
rbind( |
784 |
"", |
|
785 | 25x |
matrix("xx", nrow = nrow(df), ncol = ncol(df)) |
786 |
) |
|
787 |
) |
|
788 | ||
789 | 25x |
ret <- matrix_print_form( |
790 | 25x |
strings = strings, |
791 | 25x |
aligns = aligns, |
792 | 25x |
spans = matrix(1, nrow = fnr, ncol = fnc), |
793 | 25x |
formats = formats, ## matrix("xx", nrow = fnr, ncol = fnc), |
794 | 25x |
row_info = rowdf, |
795 | 25x |
has_topleft = FALSE, |
796 | 25x |
nlines_header = 1, |
797 | 25x |
nrow_header = 1, |
798 | 25x |
has_rowlabs = TRUE |
799 |
) |
|
800 | 25x |
mform_build_refdf(ret) |
801 |
} |
|
802 | ||
803 | ||
804 |
map_to_new <- function(old, map) { |
|
805 | 150x |
inds <- match(old, map$old_idx) |
806 | 150x |
map$new_idx[inds] |
807 | ||
808 |
} |
|
809 | ||
810 | ||
811 |
reconstruct_basic_fnote_list <- function(mf) { |
|
812 | 111x |
refdf <- mf_fnote_df(mf) |
813 | 111x |
if(NROW(refdf) == 0) |
814 | 71x |
return(NULL) |
815 | 40x |
refdf <- refdf[!duplicated(refdf$symbol),] |
816 | 40x |
paste0("{", refdf$symbol, "} - ", refdf$msg) |
817 |
} |
|
818 | ||
819 | ||
820 |
fix_fnote_df <- function(df) { |
|
821 | 41x |
ind_symb <- df$symbol == as.character(df$ref_index) |
822 | 41x |
df$ref_index <- seq_len(nrow(df)) |
823 | 41x |
df$symbol[ind_symb] <- as.character(df$ref_index[ind_symb]) |
824 | 41x |
df |
825 |
} |
|
826 | ||
827 | ||
828 | ||
829 | ||
830 | ||
831 | ||
832 | ||
833 |
.mf_subset_core_mats <- function(mf, i, row = TRUE) { |
|
834 | 109x |
fillnum <- if(row) nrow(mf_strings(mf)) - mf_nlheader(mf) else ncol(mf) |
835 | 109x |
if(is.logical(i) || all(i < 0)) |
836 | ! |
i <- seq_len(fillnum)[i] |
837 | ||
838 | 109x |
if(row) { |
839 | 41x |
nlh <- mf_nlheader(mf) |
840 | 41x |
ncolrows <- mf_nrheader(mf) |
841 | 41x |
i_mat <- c(seq_len(nlh), which(mf_lgrouping(mf) %in% (i + ncolrows))) |
842 | 41x |
j_mat <- seq_len(ncol(mf_strings(mf))) |
843 |
} else { |
|
844 | 68x |
nlabcol <- as.integer(mf_has_rlabels(mf)) |
845 | 68x |
i_mat <- seq_len(nrow(mf_strings(mf))) |
846 | 68x |
j_mat <- c(seq_len(nlabcol), i + nlabcol) |
847 |
} |
|
848 | ||
849 | ||
850 | 109x |
mf_strings(mf) <- mf_strings(mf)[i_mat, j_mat, drop = FALSE] |
851 | 109x |
mf_lgrouping(mf) <- as.integer(as.factor(mf_lgrouping(mf)[i_mat])) |
852 | 109x |
if(!row) |
853 | 68x |
newspans <- truncate_spans(mf_spans(mf), j_mat) #'i' is the columns here, b/c row is FALSE |
854 |
else |
|
855 | 41x |
newspans <- mf_spans(mf)[i_mat, j_mat, drop = FALSE] |
856 | 109x |
mf_spans(mf) <- newspans |
857 | 109x |
mf_formats(mf) <- mf_formats(mf)[i_mat, j_mat, drop = FALSE] |
858 | ||
859 | 109x |
mf_aligns(mf) <- mf_aligns(mf)[i_mat, j_mat, drop = FALSE] |
860 | 109x |
if(!row) { |
861 | 68x |
mf_ncol(mf) <- length(i) |
862 | 68x |
if(!is.null(mf_col_widths(mf))) |
863 | 68x |
mf_col_widths(mf) <- mf_col_widths(mf)[j_mat] |
864 |
} |
|
865 | 109x |
mf |
866 |
} |
|
867 | ||
868 |
## ugh. spans are **way** more of a pain than I expected x.x |
|
869 |
truncate_one_span <- function(spanrow, j) { |
|
870 | 1956x |
i <- 1 |
871 | 1956x |
len <- length(spanrow) |
872 | 1956x |
while(i < len) { |
873 | 22365x |
spnlen <- spanrow[i] |
874 | 22365x |
inds <- seq(i, i + spnlen - 1) |
875 | 22365x |
newspnlen <- sum(inds %in% j) |
876 | 22365x |
spanrow[inds] <- newspnlen |
877 | 22365x |
i <- i + spnlen |
878 |
} |
|
879 | 1956x |
spanrow[j] |
880 |
} |
|
881 | ||
882 |
truncate_spans <- function(spans, j) { |
|
883 | 68x |
if (length(spans[1,]) == 1){ |
884 | ! |
as.matrix(apply(spans, 1, truncate_one_span, j = j)) |
885 |
} |
|
886 |
else |
|
887 | 68x |
t(apply(spans, 1, truncate_one_span, j = j)) |
888 |
} |
|
889 | ||
890 | ||
891 |
mpf_subset_rows <- function(mf, i) { |
|
892 | 41x |
nlh <- mf_nlheader(mf) |
893 | 41x |
lgrps <- mf_lgrouping(mf) |
894 | 41x |
row_lgrps <- tail(lgrps, -1*nlh) |
895 | 41x |
nrs <- length(unique(row_lgrps)) |
896 | 41x |
ncolrows <- length(unique(lgrps[seq_len(nlh)])) |
897 | ||
898 | 41x |
ncs <- ncol(mf) |
899 | 41x |
mf <- .mf_subset_core_mats(mf, i, row = TRUE) |
900 | 41x |
map <- data.frame(old_idx = c(seq_len(ncolrows), i + ncolrows), |
901 | 41x |
new_idx = c(seq_len(ncolrows), ncolrows + order(i))) |
902 | ||
903 | 41x |
row_map <- data.frame(old_idx = i, new_idx = order(i)) |
904 | ||
905 | 41x |
refdf <- mf_fnote_df(mf) |
906 | ||
907 | 41x |
old_nas <- is.na(refdf$row) |
908 | 41x |
refdf$row <- map_to_new(refdf$row, row_map) |
909 | 41x |
refdf <- refdf[old_nas | !is.na(refdf$row),] |
910 | 41x |
refdf <- fix_fnote_df(refdf) |
911 | 41x |
mf_fnote_df(mf) <- refdf |
912 | ||
913 | 41x |
rinfo <- mf_rinfo(mf) |
914 | ||
915 | 41x |
rinfo <- rinfo[rinfo$abs_rownumber %in% i,] |
916 | ||
917 | 41x |
rinfo$abs_rownumber <- map_to_new(rinfo$abs_rownumber, row_map) |
918 | 41x |
mf_rinfo(mf) <- rinfo |
919 | ||
920 | 41x |
mf <- shove_refdf_into_rowinfo(mf) |
921 | 41x |
mf_rfnotes(mf) <- reconstruct_basic_fnote_list(mf) |
922 | 41x |
mf |
923 | ||
924 |
} |
|
925 | ||
926 | ||
927 | ||
928 |
## we only care about referential footnotes, cause |
|
929 |
## they are currently the only place we're tracking |
|
930 |
## column information that will need to be touched up |
|
931 |
## but lets be careful and do a bit more anyway |
|
932 |
mpf_subset_cols <- function(mf, j) { |
|
933 | ||
934 | 68x |
nc <- ncol(mf) |
935 | 68x |
if(is.logical(j) || all(j < 0)) |
936 | ! |
j <- seq_len(nc)[j] |
937 | 68x |
if(any(j < 0)) |
938 | ! |
stop("cannot mix negative and positive indices") |
939 | ||
940 | 68x |
if(length(unique(j)) != length(j)) |
941 | ! |
stop("duplicated columns are not allowed when subsetting a matrix print form objects") |
942 | ||
943 | ||
944 |
# j_mat <- c(if(mf_has_topleft(mf)) seq_len(nlabcol), j + nlabcol) |
|
945 | 68x |
map <- data.frame(old_idx = j, new_idx = order(j)) |
946 | ||
947 |
## this has to happen before the remap inher |
|
948 | 68x |
refdf <- mf_fnote_df(mf) |
949 | ||
950 | 68x |
mf <- .mf_subset_core_mats(mf, j, row = FALSE) |
951 | ||
952 | ||
953 |
## future proofing (pipe dreams) |
|
954 |
## uncomment if we ever manage to have col info information on MPFs |
|
955 |
## if(!is.null(mf_cinfo(mf))) { |
|
956 |
## cinfo <- mf_cinfo(mf) |
|
957 |
## cinfo <- cinfo[j, , drop = FALSE] |
|
958 |
## cinfo$abs_pos <- map_to_new(cinfo$abs_pos, map) |
|
959 |
## mf_cinfo(mf) <- mf |
|
960 |
## } |
|
961 | ||
962 | ||
963 | ||
964 | 68x |
keep <- is.na(refdf$col) | refdf$col %in% j |
965 | 68x |
refdf <- refdf[keep, , drop = FALSE] |
966 | ||
967 | 68x |
refdf$col <- map_to_new(refdf$col, map) |
968 | 68x |
mf_fnote_df(mf) <- refdf |
969 | 68x |
mf <- shove_refdf_into_rowinfo(mf) |
970 | 68x |
mf_rfnotes(mf) <- reconstruct_basic_fnote_list(mf) |
971 | 68x |
mf_ncol(mf) <- length(j) |
972 | 68x |
mf |
973 |
} |
1 |
# `toString` ---- |
|
2 | ||
3 |
## this can't be tested from within R |
|
4 |
# nocov start |
|
5 |
#' @importFrom stats na.omit |
|
6 |
#' @importFrom utils head tail localeToCharset |
|
7 |
#' @import checkmate |
|
8 | ||
9 |
d_hsep_factory <- function() { |
|
10 |
warn_sent <- FALSE |
|
11 |
function() { |
|
12 |
if (any(grepl("^UTF", localeToCharset()))) { |
|
13 |
"\u2014" |
|
14 |
} else { |
|
15 |
if (!warn_sent && interactive()) { |
|
16 |
message( |
|
17 |
"Detected non-UTF charset. Falling back to '-' ", |
|
18 |
"as default header/body separator. This warning ", |
|
19 |
"will only be shown once per R session." |
|
20 |
) |
|
21 |
warn_sent <<- TRUE |
|
22 |
} |
|
23 |
"-" |
|
24 |
} |
|
25 |
} |
|
26 |
} |
|
27 | ||
28 |
#' Default horizontal Separator |
|
29 |
#' |
|
30 |
#' The default horizontal separator character which can be |
|
31 |
#' displayed in the current `charset` for use in rendering table-likes. |
|
32 |
#' |
|
33 |
#' @return `unicode` 2014 (long dash for generating solid horizontal line) |
|
34 |
#' if in a locale that uses a UTF character set, otherwise an ASCII hyphen |
|
35 |
#' with a once-per-session warning. |
|
36 |
#' |
|
37 |
#' @export |
|
38 |
#' @examples |
|
39 |
#' default_hsep() |
|
40 |
default_hsep <- d_hsep_factory() |
|
41 | ||
42 |
# nocov end |
|
43 | ||
44 |
.calc_cell_widths <- function(mat, colwidths, col_gap) { |
|
45 | 142x |
spans <- mat$spans |
46 | 142x |
keep_mat <- mat$display |
47 | 142x |
body <- mat$strings |
48 | ||
49 | 142x |
nr <- nrow(body) |
50 | ||
51 | 142x |
cell_widths_mat <- matrix(rep(colwidths, nr), nrow = nr, byrow = TRUE) |
52 | 142x |
nc <- ncol(cell_widths_mat) |
53 | ||
54 | 142x |
for (i in seq_len(nrow(body))) { |
55 | 2691x |
if (any(!keep_mat[i, ])) { # any spans? |
56 | 6x |
j <- 1 |
57 | 6x |
while (j <= nc) { |
58 | 10x |
nj <- spans[i, j] |
59 | 10x |
j <- if (nj > 1) { |
60 | 6x |
js <- seq(j, j + nj - 1) |
61 | 6x |
cell_widths_mat[i, js] <- sum(cell_widths_mat[i, js]) + col_gap * (nj - 1) |
62 | 6x |
j + nj |
63 |
} else { |
|
64 | 4x |
j + 1 |
65 |
} |
|
66 |
} |
|
67 |
} |
|
68 |
} |
|
69 | 142x |
cell_widths_mat |
70 |
} |
|
71 | ||
72 | ||
73 | ||
74 |
do_cell_fnotes_wrap <- function(mat, widths, max_width, tf_wrap) { |
|
75 | ||
76 | 84x |
col_gap <- mf_colgap(mat) |
77 | 84x |
ncchar <- sum(widths) + (length(widths) - 1) * col_gap |
78 | 84x |
inset <- table_inset(mat) |
79 | ||
80 |
## Text wrapping checks |
|
81 | 84x |
if (tf_wrap) { |
82 | 19x |
if (is.null(max_width)) { |
83 | 3x |
max_width <- getOption("width", 80L) |
84 | 16x |
} else if (is.character(max_width) && identical(max_width, "auto")) { |
85 | ! |
max_width <- ncchar + inset |
86 |
} |
|
87 | 19x |
assert_number(max_width, lower = 0) |
88 |
} |
|
89 | ||
90 |
## Check for having the right number of widths |
|
91 | 84x |
stopifnot(length(widths) == ncol(mat$strings)) |
92 | ||
93 |
## format the to ASCII |
|
94 | 84x |
cell_widths_mat <- .calc_cell_widths(mat, widths, col_gap) |
95 |
## wrap_string calls strwrap, which destroys whitespace so we need to make |
|
96 |
## sure to put the indents back in |
|
97 | ||
98 |
## See if indentation is properly set |
|
99 | 84x |
ind_from_mf <- mf_rinfo(mat)$indent > 0 |
100 | 84x |
nlh <- mf_nlheader(mat) |
101 | 84x |
ind_std <- paste0(rep(" ", mat$indent_size), collapse = "") |
102 |
## Body indentation |
|
103 | 84x |
old_indent <- sapply(mf_rinfo(mat)$indent, function(i) paste0(rep(ind_std, i), collapse = "")) |
104 |
## Header indentation (it happens with toplefts, not \n in titles, dealt afterwards) |
|
105 |
## NB: what about \n in topleft? -> not supported |
|
106 | 84x |
header_indent <- gsub("^([[:space:]]*).*", "\\1", mat$strings[1:nlh, 1]) # Supposedly never with empty strings " " |
107 | 84x |
old_indent <- c(header_indent, old_indent) |
108 | 84x |
need_reindent <- nzchar(old_indent) |
109 |
## Check for which row has indent |
|
110 | 84x |
ind_from_strings <- nchar(old_indent)[-seq_len(nlh)] > 0 |
111 | 84x |
if (!all(ind_from_strings == ind_from_mf)) { |
112 |
stop("Row-info and string indentations are different.", # nocov |
|
113 |
" Please contact the maintainer, this should not happen.") # nocov |
|
114 |
} |
|
115 | 84x |
ori_mflg <- mf_lgrouping(mat) # Original groups |
116 | 84x |
reindent_old_idx <- ori_mflg[need_reindent] # Indent groups bf wrap |
117 | ||
118 |
## Taking care in advance of indented word wrappings |
|
119 | 84x |
cell_widths_mat[need_reindent, 1] <- cell_widths_mat[need_reindent, 1] - nchar(old_indent)[need_reindent] |
120 | ||
121 |
## Case in which the indentation is taking too much space vs desired wrapping |
|
122 | 84x |
if (any(cell_widths_mat < 0)) { |
123 | 1x |
col_culprits <- apply(cell_widths_mat, 2, function(i) any(i < 0)) |
124 | 1x |
stop( |
125 | 1x |
"Inserted width(s) for column(s) ", which(col_culprits), |
126 | 1x |
" is(are) not wide enough for the desired indentation." |
127 |
) |
|
128 |
} |
|
129 | ||
130 | 83x |
new_strings <- matrix( |
131 | 83x |
unlist(mapply(wrap_string, |
132 | 83x |
str = mat$strings, |
133 | 83x |
max_width = cell_widths_mat, |
134 | 83x |
hard = TRUE |
135 |
)), |
|
136 | 83x |
ncol = ncol(mat$strings) |
137 |
) |
|
138 | 83x |
mat$strings <- new_strings |
139 | ||
140 |
## XXXXX this is wrong and will break for listings cause we don't know when |
|
141 |
## we need has_topleft to be FALSE!!!!!!!!!! |
|
142 | 83x |
mat <- mform_handle_newlines(mat) |
143 | ||
144 |
## Indent groups after newline |
|
145 | 83x |
reindent_new_idx <- mf_lgrouping(mat) %in% reindent_old_idx |
146 | 83x |
if (anyNA(reindent_new_idx)) { |
147 |
stop("Unable to remap indenting after cell content text wrapping. ", # nocov |
|
148 |
"Please contact the maintainer, this should not happen.") # nocov |
|
149 |
} |
|
150 | ||
151 |
## Adding the indentation back in |
|
152 | 83x |
ind_v <- NULL |
153 | 83x |
for (i in mf_lgrouping(mat)[reindent_new_idx]) { |
154 | 4x |
ind_v <- c(ind_v, which(i == ori_mflg)[1]) |
155 |
} |
|
156 | 83x |
new_indent <- old_indent[ind_v] |
157 | ||
158 |
## Additional safety check |
|
159 | 83x |
if (length(new_indent) > 0 && !all(nzchar(new_indent))) { |
160 |
stop("Recovered indentation contains empty strings. This is an", # nocov |
|
161 |
" indexing problem, please contact the maintainer, this should not happen.") # nocov |
|
162 |
} |
|
163 | ||
164 |
## Indentation is different for topleft material |
|
165 | 83x |
if (isTRUE(mf_has_topleft(mat))) { |
166 |
## mf_nlheader counts actual header lines while mf_nrheader is 'virtual' |
|
167 |
## A bit of an hack, but unforeseen behavior, related to \n in topleft is not supported |
|
168 |
## Therefore, this still suppose that we dealt with \n in the cols before |
|
169 | 2x |
indx_topleft <- which(reindent_new_idx[1:nlh]) |
170 | 2x |
new_indent[seq_along(indx_topleft)] <- old_indent[indx_topleft] |
171 |
} |
|
172 | ||
173 |
## Main addition of the 'saved' indentation to strings |
|
174 | 83x |
mf_strings(mat)[reindent_new_idx, 1] <- paste0( |
175 | 83x |
new_indent, |
176 | 83x |
mat$strings[reindent_new_idx, 1] |
177 |
) |
|
178 |
## this updates extents in rinfo AND nlines in ref_fnotes_df |
|
179 | 83x |
mat <- update_mf_nlines(mat, max_width = max_width) |
180 | 83x |
mat |
181 |
} |
|
182 | ||
183 |
## take a character vector and return whether the value is |
|
184 |
## a string version of a number or not |
|
185 |
is_number_str <- function(vec) { |
|
186 | ! |
is.na(as.numeric(vec)) |
187 |
} |
|
188 | ||
189 |
is_dec_align <- function(vec) { |
|
190 |
# "c" is not an alignment method we define in `formatters`, |
|
191 |
# but the reverse dependency package `tables` will need |
|
192 | 378x |
sdiff <- setdiff(vec, c(list_valid_aligns(), "c")) |
193 | 378x |
if(length(sdiff) > 0) |
194 | ! |
stop("Invalid text-alignment(s): ", |
195 | ! |
paste(sdiff, collapse = ", ")) |
196 | 378x |
grepl("dec", vec) |
197 |
} |
|
198 | ||
199 | 233x |
any_dec_align <- function(vec) any(is_dec_align(vec)) |
200 | ||
201 |
#' Decimal Alignment |
|
202 |
#' |
|
203 |
#' @description Aligning decimal values of string matrix. Allowed alignments are: `dec_left`, |
|
204 |
#' `dec_right` and `decimal`. |
|
205 |
#' |
|
206 |
#' @param string_mat character matrix. String matrix component of matrix print form object. |
|
207 |
#' @param align_mat character matrix. Aligns matrix component of matrix print form object. |
|
208 |
#' Should contain either `dec_left`, `dec_right` or `decimal` for values to be decimal aligned. |
|
209 |
#' |
|
210 |
#' @details Decimal alignment left and right (`dec_left` and `dec_right`) are different to |
|
211 |
#' center decimal alignment `decimal` only in the case some padding is present. This may |
|
212 |
#' happen if column widths are wider by setting parameters `widths` in `toString` or |
|
213 |
#' `colwidths` in `paginate_*` accordingly. It will be also the case (more common) of |
|
214 |
#' wider column names. Decimal alignment is not supported along with cell wrapping. |
|
215 |
#' |
|
216 |
#' @examples |
|
217 |
#' dfmf <- basic_matrix_form(mtcars[1:5,]) |
|
218 |
#' aligns <- mf_aligns(dfmf) |
|
219 |
#' aligns[, -c(1)] <- "dec_left" |
|
220 |
#' decimal_align(mf_strings(dfmf), aligns) |
|
221 |
#' |
|
222 |
#' @return Processed string matrix of matrix print form with decimal aligned values. |
|
223 |
#' |
|
224 |
#' @seealso [toString] and [MatrixPrintForm] |
|
225 |
#' |
|
226 |
#' @export |
|
227 |
decimal_align <- function(string_mat, align_mat) { |
|
228 |
## Evaluate if any values are to be decimal aligned |
|
229 | 45x |
if (!any_dec_align(align_mat)) { |
230 | ! |
return(string_mat) |
231 |
} |
|
232 | 45x |
for (i in seq(1, ncol(string_mat))) { |
233 |
## Take a column and its decimal alignments |
|
234 | 145x |
col_i <- as.character(string_mat[, i]) |
235 | 145x |
align_col_i <- is_dec_align(align_mat[, i]) |
236 | ||
237 |
## !( A || B) -> !A && !B DeMorgan's Law |
|
238 |
## Are there any values to be decimal aligned? safe if |
|
239 | 145x |
if (any(align_col_i) && any(!grepl("^[0-9]\\.", col_i))) { |
240 |
## Extract values not to be aligned (NAs, non-numbers, |
|
241 |
## doesn't say "decimal" in alignment matrix) |
|
242 |
## XXX FIXME because this happens after formatting, we can't tell the difference between |
|
243 |
## non-number strings which come from na_str+ NA value and strings which just aren't numbers. |
|
244 |
## this is a problem that should eventually be fixed. |
|
245 | 82x |
nas <- vapply(col_i, is.na, FUN.VALUE = logical(1)) |
246 | 82x |
nonnum <- !grepl("[0-9]", col_i) |
247 |
## No grepl("[a-zA-Z]", col_i) because this excludes N=xx, e.g. |
|
248 | 82x |
nonalign <- nas | nonnum | !align_col_i |
249 | 82x |
col_ia <- col_i[!nonalign] |
250 | ||
251 |
## Do decimal alignment |
|
252 | 82x |
if (length(col_ia) > 0) { |
253 |
# Special case: scientific notation |
|
254 | 82x |
has_sc_not <- grepl("\\d+[e|E][\\+|\\-]\\d+", col_ia) |
255 | 82x |
if(any(has_sc_not)) { |
256 | 1x |
stop("Found values using scientific notation between the ones that", |
257 | 1x |
" needs to be decimal aligned (aligns is decimal, dec_left or dec_right).", |
258 | 1x |
" Please consider using format functions to get a complete decimal ", |
259 | 1x |
"(e.g. formatC).") |
260 |
} |
|
261 | ||
262 |
## Count the number of numbers in the string |
|
263 | 81x |
matches <- gregexpr("\\d+\\.\\d+|\\d+", col_ia) |
264 | 81x |
more_than_one <- vapply(matches, function(x) { |
265 | 685x |
sum(attr(x, "match.length") > 0) > 1 |
266 | 81x |
}, logical(1)) |
267 |
## Throw error in case any have more than 1 numbers |
|
268 | 81x |
if (any(more_than_one)) { |
269 | 2x |
stop("Decimal alignment is not supported for multiple values. ", |
270 | 2x |
"Found the following string with multiple numbers ", |
271 | 2x |
"(first 3 selected from column ", col_i[1],"): '", |
272 | 2x |
paste0(col_ia[more_than_one][seq(1, 3)], |
273 | 2x |
collapse = "', '"), "'") |
274 |
} |
|
275 |
## General split (only one match -> the first) |
|
276 | 79x |
main_regexp <- regexpr("\\d+", col_ia) |
277 | 79x |
left <- regmatches(col_ia, main_regexp, invert = FALSE) |
278 | 79x |
right <- regmatches(col_ia, main_regexp, invert = TRUE) |
279 | 79x |
right <- sapply(right, "[[", 2) |
280 | 79x |
something_left <- sapply(strsplit(col_ia, "\\d+"), "[[", 1) |
281 | 79x |
left <- paste0(something_left, left) |
282 | 79x |
if (!checkmate::test_set_equal(paste0(left, right), col_ia)) |
283 | ! |
stop("Split string list lost some piece along the way. This ", |
284 | ! |
"should not have happened. Please contact the maintainer.") # nocov |
285 | 79x |
separator <- sapply(right, function(x) { |
286 | 639x |
if (nzchar(x)) { |
287 | 346x |
substr(x, 1, 1) |
288 |
} else { |
|
289 | 293x |
c(" ") |
290 |
} |
|
291 | 79x |
}, USE.NAMES = FALSE) |
292 | 79x |
right <- sapply(right, function(x) { |
293 | 639x |
if (nchar(x) > 1) { |
294 | 314x |
substr(x, 2, nchar(x)) |
295 |
} else { |
|
296 | 325x |
c("") |
297 |
} |
|
298 | 79x |
}, USE.NAMES = FALSE) |
299 |
## figure out whether we need space separators (at least one had a "." or not) |
|
300 | 79x |
if(!any(grepl("[^[:space:]]", separator))) |
301 | 26x |
separator <- gsub("[[:space:]]*", "", separator) |
302 |
## modify the piece with spaces |
|
303 | 79x |
left_mod <- paste0(spaces(max(nchar(left), na.rm = TRUE) - nchar(left)), left) |
304 | 79x |
right_mod <- paste0(right, spaces(max(nchar(right), na.rm = TRUE) - nchar(right))) |
305 |
# Put everything together |
|
306 | 79x |
aligned <- paste(left_mod, separator, right_mod, sep = "") |
307 | 79x |
string_mat[!nonalign, i] <- aligned |
308 |
} |
|
309 |
} |
|
310 |
} |
|
311 | 42x |
string_mat |
312 |
} |
|
313 | ||
314 |
#' @rdname tostring |
|
315 |
#' |
|
316 |
#' @inheritParams MatrixPrintForm |
|
317 |
#' @param widths numeric (or NULL). (proposed) widths for the columns |
|
318 |
#' of \code{x}. The expected length of this numeric vector can be |
|
319 |
#' retrieved with `ncol() + 1` as the column of row names must |
|
320 |
#' also be considered. |
|
321 |
#' @param hsep character(1). Characters to repeat to create |
|
322 |
#' header/body separator line. |
|
323 |
#' @param tf_wrap logical(1). Should the texts for title, subtitle, |
|
324 |
#' and footnotes be wrapped? |
|
325 |
#' @param max_width integer(1), character(1) or NULL. Width that title |
|
326 |
#' and footer (including footnotes) materials should be |
|
327 |
#' word-wrapped to. If NULL, it is set to the current print width |
|
328 |
#' of the session (`getOption("width")`). If set to `"auto"`, |
|
329 |
#' the width of the table (plus any table inset) is used. Ignored |
|
330 |
#' completely if `tf_wrap` is `FALSE`. |
|
331 |
#' |
|
332 |
#' @details |
|
333 |
#' |
|
334 |
#' Manual insertion of newlines is not supported when `tf_wrap` is on |
|
335 |
#' and will result in a warning and undefined wrapping behavior. Passing |
|
336 |
#' vectors of already split strings remains supported, however in this |
|
337 |
#' case each string is word-wrapped separately with the behavior |
|
338 |
#' described above. |
|
339 |
#' |
|
340 |
#' @examples |
|
341 |
#' mform <- basic_matrix_form(mtcars) |
|
342 |
#' cat(toString(mform)) |
|
343 |
#' |
|
344 |
#' @return A character string containing the ASCII rendering |
|
345 |
#' of the table-like object represented by `x` |
|
346 |
#' |
|
347 |
#' @exportMethod toString |
|
348 |
setMethod("toString", "MatrixPrintForm", function(x, |
|
349 |
widths = NULL, |
|
350 |
tf_wrap = FALSE, |
|
351 |
max_width = NULL, |
|
352 |
col_gap = mf_colgap(x), |
|
353 |
hsep = default_hsep()) { |
|
354 | 63x |
assert_flag(tf_wrap) |
355 | ||
356 | 63x |
mat <- matrix_form(x, indent_rownames = TRUE) |
357 | 63x |
inset <- table_inset(mat) |
358 | ||
359 |
# if cells are decimal aligned, run propose column widths |
|
360 |
# if the provided widths is less than proposed width, return an error |
|
361 | 63x |
if (any_dec_align(mf_aligns(mat))) { |
362 | 22x |
aligned <- propose_column_widths(x) |
363 | ||
364 |
# catch any columns that require widths more than what is provided |
|
365 | 20x |
if (!is.null(widths)) { |
366 | 9x |
how_wide <- sapply(seq_along(widths), function(i) c(widths[i] - aligned[i])) |
367 | 9x |
too_wide <- how_wide < 0 |
368 | 9x |
if (any(too_wide)) { |
369 | 2x |
desc_width <- paste(paste( |
370 | 2x |
names(which(too_wide)), |
371 | 2x |
paste0("(", how_wide[too_wide], ")") |
372 | 2x |
), collapse = ", ") |
373 | 2x |
stop( |
374 | 2x |
"Inserted width(s) for column(s) ", desc_width, |
375 | 2x |
" is(are) not wide enough for the desired alignment." |
376 |
) |
|
377 |
} |
|
378 |
} |
|
379 |
} |
|
380 | ||
381 | 59x |
if (is.null(widths)) { |
382 | 49x |
widths <- mf_col_widths(x) %||% propose_column_widths(x) |
383 |
} else { |
|
384 | 10x |
mf_col_widths(x) <- widths |
385 |
} |
|
386 | 59x |
ncchar <- sum(widths) + (length(widths) - 1) * col_gap |
387 | ||
388 |
## Text wrapping checks |
|
389 | 59x |
if (tf_wrap) { |
390 | 16x |
if (is.null(max_width)) { |
391 | 11x |
max_width <- getOption("width", 80L) |
392 | 5x |
} else if (is.character(max_width) && identical(max_width, "auto")) { |
393 | 2x |
max_width <- ncchar + inset |
394 |
} |
|
395 | 16x |
assert_number(max_width, lower = 0) |
396 |
} |
|
397 | ||
398 | 59x |
mat <- do_cell_fnotes_wrap(mat, widths, max_width = max_width, tf_wrap = tf_wrap) |
399 | ||
400 | 58x |
body <- mf_strings(mat) |
401 | 58x |
aligns <- mf_aligns(mat) |
402 | 58x |
keep_mat <- mf_display(mat) |
403 |
## spans <- mat$spans |
|
404 |
## ri <- mat$row_info |
|
405 | 58x |
ref_fnotes <- mf_rfnotes(mat) |
406 | 58x |
nl_header <- mf_nlheader(mat) |
407 | ||
408 | 58x |
cell_widths_mat <- .calc_cell_widths(mat, widths, col_gap) |
409 | ||
410 |
# decimal alignment |
|
411 | 58x |
if (any_dec_align(aligns)) { |
412 | 18x |
body <- decimal_align(body, aligns) |
413 |
} |
|
414 | ||
415 | 58x |
content <- matrix(mapply(padstr, body, cell_widths_mat, aligns), ncol = ncol(body)) |
416 | 58x |
content[!keep_mat] <- NA |
417 |
# apply(content, 1, function(x) sum(nchar(x), na.rm = TRUE)) |
|
418 | ||
419 | 58x |
gap_str <- strrep(" ", col_gap) |
420 | ||
421 | 58x |
div <- substr(strrep(hsep, ncchar), 1, ncchar) |
422 | 58x |
txt_head <- apply(head(content, nl_header), 1, .paste_no_na, collapse = gap_str) |
423 | 58x |
sec_seps_df <- x$row_info[, c("abs_rownumber", "trailing_sep"), drop = FALSE] |
424 | 58x |
if (!is.null(sec_seps_df) && any(!is.na(sec_seps_df$trailing_sep))) { |
425 | 1x |
bdy_cont <- tail(content, -nl_header) |
426 |
## unfortunately we count "header rows" wrt line grouping so it |
|
427 |
## doesn't match the real (i.e. body) rows as is |
|
428 | 1x |
row_grouping <- tail(x$line_grouping, -nl_header) - mf_nrheader(x) |
429 | 1x |
nrbody <- NROW(bdy_cont) |
430 | 1x |
stopifnot(length(row_grouping) == nrbody) |
431 |
## all rows with non-NA section divs and the final row (regardless of NA status) |
|
432 |
## fixes #77 |
|
433 | 1x |
sec_seps_df <- sec_seps_df[unique(c( |
434 | 1x |
which(!is.na(sec_seps_df$trailing_sep)), |
435 | 1x |
NROW(sec_seps_df) |
436 |
)), ] |
|
437 | 1x |
txt_body <- character() |
438 | 1x |
sec_strt <- 1 |
439 | 1x |
section_rws <- sec_seps_df$abs_rownumber |
440 | 1x |
for (i in seq_len(NROW(section_rws))) { |
441 | 2x |
cur_rownum <- section_rws[i] |
442 | 2x |
sec_end <- max(which(row_grouping == cur_rownum)) |
443 | 2x |
txt_body <- c( |
444 | 2x |
txt_body, |
445 | 2x |
apply(bdy_cont[seq(sec_strt, sec_end), , drop = FALSE], |
446 | 2x |
1, |
447 | 2x |
.paste_no_na, |
448 | 2x |
collapse = gap_str |
449 |
), |
|
450 |
## don't print section dividers if they would be the last thing before the |
|
451 |
## footer divider |
|
452 |
## this also ensures an extraneous sec div won't be printed if we have non-sec-div |
|
453 |
## rows after the last sec div row (#77) |
|
454 | 2x |
if (sec_end < nrbody) { |
455 | 1x |
substr( |
456 | 1x |
strrep(sec_seps_df$trailing_sep[i], ncchar), 1, |
457 | 1x |
ncchar - inset |
458 |
) |
|
459 |
} |
|
460 |
) |
|
461 | 2x |
sec_strt <- sec_end + 1 |
462 |
} |
|
463 |
} else { |
|
464 | 57x |
txt_body <- apply(tail(content, -nl_header), 1, .paste_no_na, collapse = gap_str) |
465 |
} |
|
466 | ||
467 | ||
468 | 58x |
allts <- all_titles(x) |
469 | ||
470 | 58x |
allfoots <- list( |
471 | 58x |
"main_footer" = main_footer(x), |
472 | 58x |
"prov_footer" = prov_footer(x), |
473 | 58x |
"ref_footnotes" = ref_fnotes |
474 |
) |
|
475 | 58x |
allfoots <- allfoots[!sapply(allfoots, is.null)] |
476 | ||
477 | ||
478 |
## Wrapping titles if they go beyond the horizontally allowed space |
|
479 | 58x |
if (tf_wrap) { |
480 | 16x |
new_line_warning(allts) |
481 | 16x |
allts <- wrap_txt(allts, max_width = max_width) |
482 |
} |
|
483 | ||
484 | 58x |
titles_txt <- if (any(nzchar(allts))) c(allts, "", .do_inset(div, inset)) else NULL |
485 | ||
486 |
# Wrapping footers if they go beyond the horizontally allowed space |
|
487 | 58x |
if (tf_wrap) { |
488 | 16x |
new_line_warning(allfoots) |
489 | 16x |
allfoots$main_footer <- wrap_txt(allfoots$main_footer, max_width - inset) |
490 | 16x |
allfoots$ref_footnotes <- wrap_txt(allfoots$ref_footnotes, max_width - inset) |
491 |
## no - inset here because the prov_footer is not inset |
|
492 | 16x |
allfoots$prov_footer <- wrap_txt(allfoots$prov_footer, max_width) |
493 |
} |
|
494 | ||
495 | 58x |
paste0(paste( |
496 | 58x |
c( |
497 | 58x |
titles_txt, |
498 | 58x |
.do_inset(txt_head, inset), |
499 | 58x |
.do_inset(div, inset), |
500 | 58x |
.do_inset(txt_body, inset), |
501 | 58x |
.footer_inset_helper(allfoots, div, inset) |
502 |
), |
|
503 | 58x |
collapse = "\n" |
504 | 58x |
), "\n") |
505 |
}) |
|
506 | ||
507 |
.do_inset <- function(x, inset) { |
|
508 | 322x |
if (inset == 0 || !any(nzchar(x))) { |
509 | 303x |
return(x) |
510 |
} |
|
511 | 19x |
padding <- strrep(" ", inset) |
512 | 19x |
if (is.character(x)) { |
513 | 19x |
x <- paste0(padding, x) |
514 | ! |
} else if (is(x, "matrix")) { |
515 | ! |
x[, 1] <- .do_inset(x[, 1, drop = TRUE], inset) |
516 |
} |
|
517 | 19x |
x |
518 |
} |
|
519 | ||
520 | ||
521 |
.inset_div <- function(txt, div, inset) { |
|
522 | 40x |
c(.do_inset(div, inset), "", txt) |
523 |
} |
|
524 | ||
525 |
.footer_inset_helper <- function(footers_v, div, inset) { |
|
526 | 58x |
div_done <- FALSE # nolint |
527 | 58x |
fter <- footers_v$main_footer |
528 | 58x |
prvf <- footers_v$prov_footer |
529 | 58x |
rfn <- footers_v$ref_footnotes |
530 | 58x |
footer_txt <- .do_inset(rfn, inset) |
531 | 58x |
if (any(nzchar(footer_txt))) { |
532 | 14x |
footer_txt <- .inset_div(footer_txt, div, inset) |
533 |
} |
|
534 | 58x |
if (any(vapply( |
535 | 58x |
footers_v, function(x) any(nzchar(x)), |
536 | 58x |
TRUE |
537 |
))) { |
|
538 | 26x |
if (any(nzchar(prvf))) { |
539 | 24x |
provtxt <- c( |
540 | 24x |
if (any(nzchar(fter))) "", |
541 | 24x |
prvf |
542 |
) |
|
543 |
} else { |
|
544 | 2x |
provtxt <- character() |
545 |
} |
|
546 | 26x |
footer_txt <- c( |
547 | 26x |
footer_txt, |
548 | 26x |
.inset_div( |
549 | 26x |
c( |
550 | 26x |
.do_inset(fter, inset), |
551 | 26x |
provtxt |
552 |
), |
|
553 | 26x |
div, |
554 | 26x |
inset |
555 |
) |
|
556 |
) |
|
557 |
} |
|
558 | 58x |
footer_txt |
559 |
} |
|
560 | ||
561 |
new_line_warning <- function(str_v) { |
|
562 | 32x |
if (any(unlist(sapply(str_v, grepl, pattern = "\n")))) { |
563 | 2x |
msg <- c( |
564 | 2x |
"Detected manual newlines when automatic title/footer word-wrapping is on.", |
565 | 2x |
"This is unsupported and will result in undefined behavior. Please either ", |
566 | 2x |
"utilize automatic word-wrapping with newline characters inserted, or ", |
567 | 2x |
"turn off automatic wrapping and wordwrap all contents manually by inserting ", |
568 | 2x |
"newlines." |
569 |
) |
|
570 | 2x |
warning(paste0(msg, collapse = "")) |
571 |
} |
|
572 |
} |
|
573 | ||
574 |
#' Wrap a string to within a maximum width |
|
575 |
#' @param str character(1). String to be wrapped |
|
576 |
#' @param max_width numeric(1). Maximum width, in characters, that the |
|
577 |
#' text should be wrapped at. |
|
578 |
#' @param hard logical(1). Should hard wrapping (embedding newlines in |
|
579 |
#' the incoming strings) or soft (breaking wrapped strings into vectors |
|
580 |
#' of length >1) be used. Defaults to `FALSE` (i.e. soft wrapping). |
|
581 |
#' |
|
582 |
#' @details Word wrapping happens as with \link[base:strwrap]{base::strwrap} |
|
583 |
#' with the following exception: individual words which are longer |
|
584 |
#' than `max_width` are broken up in a way that fits with the rest of the |
|
585 |
#' word wrapping. |
|
586 |
#' |
|
587 |
#' @return A string (`wrap_string` or character vector (`wrap_txt`) containing |
|
588 |
#' the hard or soft word-wrapped content. |
|
589 |
#' |
|
590 |
#' @export |
|
591 |
wrap_string <- function(str, max_width, hard = FALSE) { |
|
592 | 16149x |
stopifnot(is.character(str) && length(str) == 1) |
593 | 16149x |
naive <- strwrap(str, max_width + 1) |
594 | 16149x |
while (any(nchar(naive) > max_width)) { |
595 | 14x |
good <- character() |
596 | 14x |
bwi <- which(nchar(naive) > max_width)[1] |
597 | 14x |
curbw <- naive[bwi] |
598 | 14x |
if (bwi > 2) { |
599 | ! |
good <- c(good, naive[1:(bwi - 2)]) |
600 |
} |
|
601 | 14x |
if (bwi > 1) { |
602 | 4x |
str_before <- naive[bwi - 1] |
603 |
} else { |
|
604 | 10x |
str_before <- "" |
605 |
} |
|
606 | 14x |
room <- max_width - nchar(str_before) - (bwi > 1) |
607 | 14x |
if (room <= 0) { |
608 | 4x |
toadd <- c(str_before, substr(curbw, 1, max_width)) |
609 | 4x |
room <- 0 |
610 | 4x |
leftover <- substr(curbw, max_width + 1, nchar(curbw)) |
611 |
} else { |
|
612 | 10x |
goodpart <- substr(curbw, 1, room) |
613 | 10x |
if (nzchar(str_before)) { |
614 | ! |
toadd <- paste(str_before, goodpart) |
615 |
} else { |
|
616 | 10x |
toadd <- goodpart |
617 |
} |
|
618 | 10x |
leftover <- substr(curbw, room + 1, nchar(curbw)) |
619 |
} |
|
620 | 14x |
good <- c(good, toadd) |
621 | 14x |
if (bwi == length(naive)) { |
622 | 13x |
good <- c(good, leftover) |
623 |
} else { |
|
624 | 1x |
good <- c( |
625 | 1x |
good, |
626 | 1x |
paste(leftover, naive[bwi + 1]), |
627 | 1x |
if (bwi < length(naive) - 1) naive[seq(bwi + 2, length(naive))] |
628 |
) |
|
629 |
} |
|
630 | 14x |
str <- paste(good, collapse = " ") |
631 | 14x |
naive <- strwrap(str, max_width + 1) |
632 |
} |
|
633 | 16149x |
if (hard) { |
634 | 16016x |
naive <- paste(naive, collapse = "\n") |
635 |
} |
|
636 | 16149x |
naive |
637 |
} |
|
638 | ||
639 |
#' @param txt character. A vector of strings that should be (independently) |
|
640 |
#' text-wrapped. |
|
641 |
#' @rdname wrap_string |
|
642 |
#' @export |
|
643 |
wrap_txt <- function(txt, max_width, hard = FALSE) { |
|
644 | 113x |
unlist(lapply(txt, wrap_string, max_width = max_width, hard = hard), use.names = FALSE) |
645 |
} |
|
646 | ||
647 |
pad_vert_top <- function(x, len) { |
|
648 | 2376x |
c(x, rep("", len - length(x))) |
649 |
} |
|
650 | ||
651 |
pad_vert_bottom <- function(x, len) { |
|
652 | 78x |
c(rep("", len - length(x)), x) |
653 |
} |
|
654 | ||
655 |
pad_vec_to_len <- function(vec, len, cpadder = pad_vert_top, rlpadder = cpadder) { |
|
656 | 204x |
dat <- unlist(lapply(vec[-1], cpadder, len = len)) |
657 | 204x |
dat <- c(rlpadder(vec[[1]], len = len), dat) |
658 | 204x |
matrix(dat, nrow = len) |
659 |
} |
|
660 | ||
661 |
rep_vec_to_len <- function(vec, len, ...) { |
|
662 | 138x |
matrix(unlist(lapply(vec, rep, times = len)), |
663 | 138x |
nrow = len |
664 |
) |
|
665 |
} |
|
666 | ||
667 | ||
668 |
safe_strsplit <- function(x, split, ...) { |
|
669 | 273x |
ret <- strsplit(x, split, ...) |
670 | 273x |
lapply(ret, function(reti) if (length(reti) == 0) "" else reti) |
671 |
} |
|
672 | ||
673 |
.expand_mat_rows_inner <- function(i, mat, row_nlines, expfun, ...) { |
|
674 | 342x |
leni <- row_nlines[i] |
675 | 342x |
rw <- mat[i, ] |
676 | 342x |
if (is.character(rw)) { |
677 | 273x |
rw <- safe_strsplit(rw, "\n", fixed = TRUE) |
678 |
} |
|
679 | 342x |
expfun(rw, len = leni, ...) |
680 |
} |
|
681 | ||
682 |
expand_mat_rows <- function(mat, row_nlines = apply(mat, 1, nlines), expfun = pad_vec_to_len, ...) { |
|
683 | 22x |
rinds <- seq_len(nrow(mat)) |
684 | 22x |
exprows <- lapply(rinds, .expand_mat_rows_inner, |
685 | 22x |
mat = mat, |
686 | 22x |
row_nlines = row_nlines, |
687 | 22x |
expfun = expfun, |
688 |
... |
|
689 |
) |
|
690 | 22x |
do.call(rbind, exprows) |
691 |
} |
|
692 | ||
693 | ||
694 |
#' Transform vectors of spans (with duplication) to Visibility vector |
|
695 |
#' |
|
696 |
#' @param spans numeric. A vector of spans, with each span value repeated |
|
697 |
#' for the cells it covers. |
|
698 |
#' |
|
699 |
#' @details |
|
700 |
#' |
|
701 |
#' The values of \code{spans} are assumed to be repeated to such that |
|
702 |
#' each individual position covered by the span has the repeated value. |
|
703 |
#' |
|
704 |
#' This means that each block of values in \code{span} must be of a length |
|
705 |
#' at least equal to its value (i.e. two 2s, three 3s, etc). |
|
706 |
#' |
|
707 |
#' This function correctly handles cases where two spans of the same size |
|
708 |
#' are next to each other; i.e., a block of four 2s represents two large |
|
709 |
#' cells each of which span two individual cells. |
|
710 |
#' @export |
|
711 |
#' @note |
|
712 |
#' |
|
713 |
#' Currently no checking or enforcement is done that the vector of |
|
714 |
#' spans is valid in the sense described in the Details section above. |
|
715 |
#' @examples |
|
716 |
#' |
|
717 |
#' spans_to_viscell(c(2, 2, 2, 2, 1, 3, 3, 3)) |
|
718 |
#' @return a logical vector the same length as `spans` indicating |
|
719 |
#' whether the contents of a string vector with those spans |
|
720 |
spans_to_viscell <- function(spans) { |
|
721 | 2x |
if (!is.vector(spans)) { |
722 | ! |
spans <- as.vector(spans) |
723 |
} |
|
724 | 2x |
myrle <- rle(spans) |
725 | 2x |
unlist( |
726 | 2x |
mapply( |
727 | 2x |
function(vl, ln) { |
728 | 4x |
rep(c(TRUE, rep(FALSE, vl - 1L)), times = ln / vl) |
729 |
}, |
|
730 | 2x |
SIMPLIFY = FALSE, |
731 | 2x |
vl = myrle$values, |
732 | 2x |
ln = myrle$lengths |
733 |
), |
|
734 | 2x |
recursive = FALSE |
735 |
) |
|
736 |
} |
|
737 | ||
738 | ||
739 |
#' Propose Column Widths based on an object's `MatrixPrintForm` form |
|
740 |
#' |
|
741 |
#' The row names are also considered a column for the output |
|
742 |
#' |
|
743 |
#' @param x `MatrixPrintForm` object, or an object with a `matrix_form` |
|
744 |
#' method. |
|
745 |
#' @param indent_size numeric(1). Indent size in characters. Ignored |
|
746 |
#' when `x` is already a `MatrixPrintForm` object in favor of information |
|
747 |
#' there. |
|
748 |
#' |
|
749 |
#' @examples |
|
750 |
#' mf <- basic_matrix_form(mtcars) |
|
751 |
#' propose_column_widths(mf) |
|
752 |
#' |
|
753 |
#' @export |
|
754 |
#' @return a vector of column widths based on the content of \code{x} |
|
755 |
#' for use in printing and pagination. |
|
756 |
## ' @examples |
|
757 |
## ' library(dplyr) |
|
758 |
## ' library(rtables) |
|
759 |
## ' iris2 <- iris %>% |
|
760 |
## ' group_by(Species) %>% |
|
761 |
## ' mutate(group = as.factor(rep_len(c("a", "b"), length.out = n()))) %>% |
|
762 |
## ' ungroup() |
|
763 |
## ' |
|
764 |
## ' l <- basic_table() %>% |
|
765 |
## ' split_cols_by("Species") %>% |
|
766 |
## ' split_cols_by("group") %>% |
|
767 |
## ' analyze(c("Sepal.Length", "Petal.Width"), afun = list_wrap_x(summary) , format = "xx.xx") |
|
768 |
## ' |
|
769 |
## ' tbl <- build_table(l, iris2) |
|
770 |
## ' mf <- matrix_form(tbl) |
|
771 |
## ' propose_column_widths(mf) |
|
772 |
propose_column_widths <- function(x, indent_size = 2) { |
|
773 |
## stopifnot(is(x, "VTableTree")) |
|
774 | 67x |
if (!is(x, "MatrixPrintForm")) { |
775 | ! |
x <- matrix_form(x, indent_rownames = TRUE, indent_size = indent_size) |
776 |
} |
|
777 | 67x |
body <- mf_strings(x) |
778 | 67x |
spans <- mf_spans(x) |
779 | 67x |
aligns <- mf_aligns(x) |
780 | 67x |
display <- mf_display(x) |
781 | ||
782 |
# compute decimal alignment if asked in alignment matrix |
|
783 | 67x |
if (any_dec_align(aligns)) { |
784 | 27x |
body <- decimal_align(body, aligns) |
785 |
} |
|
786 | ||
787 | 64x |
chars <- nchar(body) |
788 | ||
789 |
# first check column widths without colspan |
|
790 | 64x |
has_spans <- spans != 1 |
791 | 64x |
chars_ns <- chars |
792 | 64x |
chars_ns[has_spans] <- 0 |
793 | 64x |
widths <- apply(chars_ns, 2, max) |
794 | ||
795 |
# now check if the colspans require extra width |
|
796 | 64x |
if (any(has_spans)) { |
797 | 1x |
has_row_spans <- apply(has_spans, 1, any) |
798 | ||
799 | 1x |
chars_sp <- chars[has_row_spans, , drop = FALSE] |
800 | 1x |
spans_sp <- spans[has_row_spans, , drop = FALSE] |
801 | 1x |
disp_sp <- display[has_row_spans, , drop = FALSE] |
802 | ||
803 | 1x |
nc <- ncol(spans) |
804 | 1x |
for (i in seq_len(nrow(chars_sp))) { |
805 | 1x |
for (j in seq_len(nc)) { |
806 | 2x |
if (disp_sp[i, j] && spans_sp[i, j] != 1) { |
807 | 1x |
i_cols <- seq(j, j + spans_sp[i, j] - 1) |
808 | ||
809 | 1x |
nchar_i <- chars_sp[i, j] |
810 | 1x |
cw_i <- widths[i_cols] |
811 | 1x |
available_width <- sum(cw_i) |
812 | ||
813 | 1x |
if (nchar_i > available_width) { |
814 |
# need to update widths to fit content with colspans |
|
815 |
# spread width among columns |
|
816 | ! |
widths[i_cols] <- cw_i + spread_integer(nchar_i - available_width, length(cw_i)) |
817 |
} |
|
818 |
} |
|
819 |
} |
|
820 |
} |
|
821 |
} |
|
822 | 64x |
widths |
823 |
} |
|
824 | ||
825 | ||
826 | ||
827 | ||
828 |
#' Pad a string and align within string |
|
829 |
#' |
|
830 |
#' @param x string |
|
831 |
#' @param n number of character of the output string, if `n < |
|
832 |
#' nchar(x)` an error is thrown |
|
833 |
#' @param just character(1). Text alignment justification to |
|
834 |
#' use. Defaults to `center`. Must be `center`, `right`, `left`, |
|
835 |
#' `dec_right`, `dec_left` or `decimal`. |
|
836 |
#' |
|
837 |
#' @export |
|
838 |
#' @examples |
|
839 |
#' |
|
840 |
#' padstr("abc", 3) |
|
841 |
#' padstr("abc", 4) |
|
842 |
#' padstr("abc", 5) |
|
843 |
#' padstr("abc", 5, "left") |
|
844 |
#' padstr("abc", 5, "right") |
|
845 |
#' |
|
846 |
#' if (interactive()) { |
|
847 |
#' padstr("abc", 1) |
|
848 |
#' } |
|
849 |
#' @return `x`, padded to be a string of `n` characters |
|
850 |
#' |
|
851 |
padstr <- function(x, n, just = list_valid_aligns()) { |
|
852 | 5015x |
just <- match.arg(just) |
853 | ||
854 | 1x |
if (length(x) != 1) stop("length of x needs to be 1 and not", length(x)) |
855 | 1x |
if (is.na(n) || !is.numeric(n) || n < 0) stop("n needs to be numeric and > 0") |
856 | ||
857 | 1x |
if (is.na(x)) x <- "<NA>" |
858 | ||
859 | 5013x |
nc <- nchar(x) |
860 | ||
861 | ! |
if (n < nc) stop("\"", x, "\" has more than ", n, " characters") |
862 | ||
863 | 5013x |
switch(just, |
864 |
center = { |
|
865 | 269x |
pad <- (n - nc) / 2 |
866 | 269x |
paste0(spaces(floor(pad)), x, spaces(ceiling(pad))) |
867 |
}, |
|
868 | 4595x |
left = paste0(x, spaces(n - nc)), |
869 | 10x |
right = paste0(spaces(n - nc), x), |
870 |
decimal = { |
|
871 | 60x |
pad <- (n - nc) / 2 |
872 | 60x |
paste0(spaces(floor(pad)), x, spaces(ceiling(pad))) |
873 |
}, |
|
874 | 44x |
dec_left = paste0(x, spaces(n - nc)), |
875 | 35x |
dec_right = paste0(spaces(n - nc), x) |
876 |
) |
|
877 |
} |
|
878 | ||
879 |
spaces <- function(n) { |
|
880 | 5500x |
strrep(" ", n) |
881 |
} |
|
882 | ||
883 | ||
884 |
.paste_no_na <- function(x, ...) { |
|
885 | 870x |
paste(na.omit(x), ...) |
886 |
} |
|
887 | ||
888 | ||
889 |
#' spread `x` into `len` elements |
|
890 |
#' |
|
891 |
#' @param x numeric(1). The number to spread |
|
892 |
#' @param len numeric(1). The number of times to repeat \code{x} |
|
893 |
#' |
|
894 |
#' @export |
|
895 |
#' @return if \code{x} is a scalar "whole number" value (see \code{\link{is.wholenumber}}), |
|
896 |
#' the value \code{x} repeated \code{len} times. If not, an error is thrown. |
|
897 |
#' @examples |
|
898 |
#' spread_integer(3, 1) |
|
899 |
#' spread_integer(0, 3) |
|
900 |
#' spread_integer(1, 3) |
|
901 |
#' spread_integer(2, 3) |
|
902 |
#' spread_integer(3, 3) |
|
903 |
#' spread_integer(4, 3) |
|
904 |
#' spread_integer(5, 3) |
|
905 |
#' spread_integer(6, 3) |
|
906 |
#' spread_integer(7, 3) |
|
907 |
spread_integer <- function(x, len) { |
|
908 | 2x |
stopifnot( |
909 | 2x |
is.wholenumber(x), length(x) == 1, x >= 0, |
910 | 2x |
is.wholenumber(len), length(len) == 1, len >= 0, |
911 | 2x |
!(len == 0 && x > 0) |
912 |
) |
|
913 | ||
914 | ||
915 | 1x |
if (len == 0) { |
916 | ! |
integer(0) |
917 |
} else { |
|
918 | 1x |
y <- rep(floor(x / len), len) |
919 | 1x |
i <- 1 |
920 | 1x |
while (sum(y) < x) { |
921 | 1x |
y[i] <- y[i] + 1 |
922 | 1x |
if (i == len) { |
923 | ! |
i <- 1 |
924 |
} else { |
|
925 | 1x |
i <- i + 1 |
926 |
} |
|
927 |
} |
|
928 | 1x |
y |
929 |
} |
|
930 |
} |
|
931 | ||
932 | ||
933 | ||
934 |
#' `is.wholenumber` |
|
935 |
#' |
|
936 |
#' @param x numeric(1). A numeric value |
|
937 |
#' @param tol numeric(1). A precision tolerance. |
|
938 |
#' |
|
939 |
#' @return \code{TRUE} if \code{x} is within \code{tol} of zero, |
|
940 |
#' \code{FALSE} otherwise. |
|
941 |
#' |
|
942 |
#' @export |
|
943 |
#' @examples |
|
944 |
#' is.wholenumber(5) |
|
945 |
#' is.wholenumber(5.00000000000000001) |
|
946 |
#' is.wholenumber(.5) |
|
947 |
#' |
|
948 |
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) { |
|
949 | 3x |
abs(x - round(x)) < tol |
950 |
} |
1 |
### This file defines the generics which make up the interface `formatters` offers. |
|
2 |
### Defining methods for these generics for a new table-like class should be fully |
|
3 |
### sufficient for hooking that class up to the `formatters` pagination and rendering |
|
4 |
### machinery. |
|
5 | ||
6 | ||
7 |
#' @import methods |
|
8 |
#' @include matrix_form.R |
|
9 |
#' |
|
10 |
#' @title Make row layout summary data.frames for use during pagination |
|
11 |
#' |
|
12 |
#' @description |
|
13 |
#' All relevant information about table rows (e.g. indentations) is summarized in a data.frames. |
|
14 |
#' This function works ONLY on `rtables` and `rlistings` objects, and not on their print counterparts |
|
15 |
#' (like `MatrixPrintForm`). |
|
16 |
#' |
|
17 |
#' @name make_row_df |
|
18 |
#' |
|
19 |
#' @param tt ANY. Object representing the table-like object to be summarized. |
|
20 |
#' @param visible_only logical(1). Should only visible aspects of the table structure be reflected in this summary. |
|
21 |
#' Defaults to \code{TRUE}. May not be supported by all methods. |
|
22 |
#' @param incontent logical(1). Internal detail do not set manually. |
|
23 |
#' @param repr_ext integer(1). Internal detail do not set manually. |
|
24 |
#' @param repr_inds integer. Internal detail do not set manually. |
|
25 |
#' @param sibpos integer(1). Internal detail do not set manually. |
|
26 |
#' @param nsibs integer(1). Internal detail do not set manually. |
|
27 |
#' @param rownum numeric(1). Internal detail do not set manually. |
|
28 |
#' @param indent integer(1). Internal detail do not set manually. |
|
29 | ||
30 |
#' @param colwidths numeric. Internal detail do not set manually. |
|
31 |
#' @param path character. Path to the (sub)table represented by |
|
32 |
#' \code{tt}. Defaults to \code{character()} |
|
33 |
#' @param max_width numeric(1) or NULL. Maximum width for title/footer |
|
34 |
#' materials. |
|
35 |
#' |
|
36 |
#' @details When \code{visible_only} is \code{TRUE} (the default), |
|
37 |
#' methods should return a data.frame with exactly one row per |
|
38 |
#' visible row in the table-like object. This is useful when |
|
39 |
#' reasoning about how a table will print, but does not reflect |
|
40 |
#' the full pathing space of the structure (though the paths which |
|
41 |
#' are given will all work as is). |
|
42 |
#' |
|
43 |
#' If supported, when \code{visible_only} is \code{FALSE}, every |
|
44 |
#' structural element of the table (in row-space) will be reflected in |
|
45 |
#' the returned data.frame, meaning the full pathing-space will be |
|
46 |
#' represented but some rows in the layout summary will not represent |
|
47 |
#' printed rows in the table as it is displayed. |
|
48 |
#' |
|
49 |
#' Most arguments beyond \code{tt} and \code{visible_only} are present so that |
|
50 |
#' `make_row_df` methods can call `make_row_df` recursively and retain information, |
|
51 |
#' and should not be set during a top-level call |
|
52 |
#' |
|
53 |
#' @note the technically present root tree node is excluded from the summary returned by |
|
54 |
#' both \code{make_row_df} and \code{make_col_df} (see `rtables::make_col_df`), as it is simply the |
|
55 |
#' row/column structure of \code{tt} and thus not useful for pathing or pagination. |
|
56 |
#' @return a data.frame of row/column-structure information used by the pagination machinery. |
|
57 |
#' |
|
58 |
#' @rdname make_row_df |
|
59 |
#' @export |
|
60 |
## nocov start |
|
61 |
setGeneric("make_row_df", function(tt, colwidths = NULL, visible_only = TRUE, |
|
62 |
rownum = 0, |
|
63 |
indent = 0L, |
|
64 |
path = character(), |
|
65 |
incontent = FALSE, |
|
66 |
repr_ext = 0L, |
|
67 |
repr_inds = integer(), |
|
68 |
sibpos = NA_integer_, |
|
69 |
nsibs = NA_integer_, |
|
70 |
max_width = NULL) { |
|
71 |
standardGeneric("make_row_df") |
|
72 |
}) |
|
73 | ||
74 |
#' @rdname make_row_df |
|
75 |
setMethod("make_row_df", "MatrixPrintForm", function(tt, colwidths = NULL, visible_only = TRUE, |
|
76 |
rownum = 0, |
|
77 |
indent = 0L, |
|
78 |
path = character(), |
|
79 |
incontent = FALSE, |
|
80 |
repr_ext = 0L, |
|
81 |
repr_inds = integer(), |
|
82 |
sibpos = NA_integer_, |
|
83 |
nsibs = NA_integer_, |
|
84 |
max_width = NULL) { |
|
85 |
stop("make_row_df can be used only on {rtables} table objects, and not on `matrix_form`-", |
|
86 |
"generated objects (MatrixPrintForm).") |
|
87 |
}) |
|
88 |
## nocov end |
|
89 | ||
90 | ||
91 |
#' Transform `rtable` to a list of matrices which can be used for outputting |
|
92 |
#' |
|
93 |
#' Although `rtables` are represented as a tree data structure when outputting the table to ASCII or HTML it is useful to |
|
94 |
#' map the `rtable` to an in between state with the formatted cells in a matrix form. |
|
95 |
#' |
|
96 |
#' @param obj ANY. Object to be transformed into a ready-to-render form (a `MatrixPrintForm` object) |
|
97 |
#' @param indent_rownames logical(1), if TRUE the column with the row names in the `strings` matrix of has indented row |
|
98 |
#' names (strings pre-fixed) |
|
99 |
#' @param expand_newlines logical(1). Should the matrix form generated |
|
100 |
#' expand rows whose values contain newlines into multiple |
|
101 |
#' 'physical' rows (as they will appear when rendered into |
|
102 |
#' ASCII). Defaults to \code{TRUE} |
|
103 |
#' @param indent_size numeric(1). Number of spaces to be used per level of indent (if supported by |
|
104 |
#' the relevant method). Defaults to 2. |
|
105 |
#' @export |
|
106 |
#' |
|
107 |
#' @details |
|
108 |
#' |
|
109 |
#' The strings in the return object are defined as follows: row labels are those determined by \code{summarize_rows} and |
|
110 |
#' cell values are determined using \code{get_formatted_cells}. |
|
111 |
#' (Column labels are calculated using a non-exported internal function. |
|
112 |
#' |
|
113 |
#' @return A `MatrixPrintForm` classed list with the following elements: |
|
114 |
#' \describe{ |
|
115 |
#' \item{strings}{The content, as it should be printed, of the top-left material, column headers, row labels, and |
|
116 |
#' cell values of \code{tt}} |
|
117 |
#' \item{spans}{The column-span information for each print-string in the strings matrix} |
|
118 |
#' \item{aligns}{The text alignment for each print-string in the strings matrix} |
|
119 |
#' \item{display}{Whether each print-string in the strings matrix should be printed or not}. |
|
120 |
#' \item{row_info}{the data.frame generated by \code{summarize_rows(tt)}} |
|
121 |
#' } |
|
122 |
#' |
|
123 |
#' With an additional \code{nrow_header} attribute indicating the number of pseudo "rows" the |
|
124 |
#' column structure defines. |
|
125 |
setGeneric("matrix_form", function(obj, |
|
126 |
indent_rownames = FALSE, |
|
127 |
expand_newlines = TRUE, |
|
128 |
indent_size = 2) { |
|
129 | 152x |
standardGeneric("matrix_form") |
130 |
}) |
|
131 | ||
132 | ||
133 |
#' @rdname matrix_form |
|
134 |
#' @export |
|
135 |
setMethod("matrix_form", "MatrixPrintForm", function(obj, |
|
136 |
indent_rownames = FALSE, |
|
137 |
expand_newlines = TRUE, |
|
138 |
indent_size = 2) { |
|
139 | 152x |
obj |
140 |
}) |
|
141 | ||
142 | ||
143 |
## Generics for `toString` and helper functions |
|
144 | ||
145 | ||
146 |
## this is where we will take word wrapping |
|
147 |
## into account when it is added |
|
148 |
## |
|
149 |
## ALL calculations of vertical space for pagination |
|
150 |
## purposes must go through nlines and divider_height!!!!!!!! |
|
151 | ||
152 |
## this will be customizable someday. I have foreseen it (spooky noises) |
|
153 |
#' Divider Height |
|
154 |
#' |
|
155 |
#' @param obj ANY. Object. |
|
156 |
#' @return The height, in lines of text, of the divider between |
|
157 |
#' header and body. Currently returns \code{1L} for the default method. |
|
158 |
#' @export |
|
159 |
#' @examples |
|
160 |
#' divider_height(mtcars) |
|
161 | 20x |
setGeneric("divider_height", function(obj) standardGeneric("divider_height")) |
162 | ||
163 |
#' @rdname divider_height |
|
164 |
#' @export |
|
165 |
setMethod( |
|
166 |
"divider_height", "ANY", |
|
167 | 20x |
function(obj) 1L |
168 |
) |
|
169 | ||
170 |
#' Number of lines required to print a value |
|
171 |
#' @param x ANY. The object to be printed |
|
172 |
#' @param colwidths numeric. Column widths (if necessary). |
|
173 |
#' @param max_width numeric(1). Width strings should be wrapped to |
|
174 |
#' when determining how many lines they require. |
|
175 |
#' @return A scalar numeric indicating the number of lines needed |
|
176 |
#' to render the object \code{x}. |
|
177 |
#' @export |
|
178 |
setGeneric( |
|
179 |
"nlines", |
|
180 | 26621x |
function(x, colwidths = NULL, max_width = NULL) standardGeneric("nlines") |
181 |
) |
|
182 | ||
183 |
## XXX beware. I think it is dangerous |
|
184 |
#' @export |
|
185 |
#' @rdname nlines |
|
186 |
setMethod( |
|
187 |
"nlines", "list", |
|
188 |
function(x, colwidths, max_width) { |
|
189 | 2x |
if (length(x) == 0) { |
190 | 1x |
0L |
191 |
} else { |
|
192 | 1x |
sum(unlist(vapply(x, nlines, NA_integer_, |
193 | 1x |
colwidths = colwidths, |
194 | 1x |
max_width = max_width |
195 |
))) |
|
196 |
} |
|
197 |
} |
|
198 |
) |
|
199 | ||
200 |
#' @export |
|
201 |
#' @rdname nlines |
|
202 |
setMethod("nlines", "NULL", function(x, colwidths, max_width) 0L) |
|
203 | ||
204 |
#' @export |
|
205 |
#' @rdname nlines |
|
206 |
setMethod("nlines", "character", function(x, colwidths, max_width) { |
|
207 | 26618x |
if (length(x) == 0) { |
208 | 1x |
return(0L) |
209 |
} |
|
210 | ||
211 | 26617x |
sum(vapply(strsplit(x, "\n", fixed = TRUE), |
212 | 26617x |