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 | 155x |
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 | 155x |
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 | 23433x |
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 | 23430x |
if (length(x) == 0) { |
208 | 1x |
return(0L) |
209 |
} |
|
210 | ||
211 | 23429x |
sum(vapply(strsplit(x, "\n", fixed = TRUE), |
212 | 23429x |
function(xi, max_width) { |
213 | 23435x |
if (length(xi) == 0) { |
214 | 111x |
1L |
215 | 23324x |
} else if (length(max_width) == 0) { ## this happens with strsplit("", "\n") |
216 | 23275x |
length(xi) |
217 |
} else { |
|
218 | 49x |
length(wrap_txt(xi, max_width)) |
219 |
} |
|
220 | 23429x |
}, 1L, |
221 | 23429x |
max_width = max_width |
222 |
)) |
|
223 |
}) |
|
224 | ||
225 | ||
226 | ||
227 |
#' @title `toString` |
|
228 |
#' |
|
229 |
#' @description Transform a complex object into a string representation ready |
|
230 |
#' to be printed or written to a plain-text file |
|
231 |
#' |
|
232 |
#' @param x ANY. Object to be prepared for rendering. |
|
233 |
#' @param ... Passed to individual methods. |
|
234 |
#' @rdname tostring |
|
235 |
#' @export |
|
236 |
setGeneric("toString", function(x, ...) standardGeneric("toString")) |
|
237 | ||
238 |
## preserve S3 behavior |
|
239 |
setMethod("toString", "ANY", base::toString) ## nocov |
|
240 | ||
241 |
#' @title Print |
|
242 |
#' |
|
243 |
#' @description Print an R object. see \code{[base::print()]} |
|
244 |
#' @inheritParams base::print |
|
245 |
#' @rdname basemethods |
|
246 |
setMethod("print", "ANY", base::print) ## nocov |
|
247 | ||
248 | ||
249 | ||
250 | ||
251 | ||
252 | ||
253 | ||
254 | ||
255 | ||
256 | ||
257 |
## General/"universal" property `getter` and `setter` generics and stubs |
|
258 | ||
259 |
#' @title Label, Name and Format accessor generics |
|
260 |
#' |
|
261 |
#' @description `Getters` and `setters` for basic, relatively universal attributes |
|
262 |
#' of "table-like" objects" |
|
263 |
#' |
|
264 |
#' @name lab_name |
|
265 |
#' @param obj ANY. The object. |
|
266 |
#' @param value character(1)/FormatSpec. The new value of the attribute. |
|
267 |
#' @return the name, format or label of \code{obj} for `getters`, or \code{obj} after modification |
|
268 |
#' for setters. |
|
269 |
#' @aliases obj_name |
|
270 |
#' @export |
|
271 | ||
272 |
## no exported methods so we do nocov |
|
273 |
# nocov start |
|
274 |
setGeneric("obj_name", function(obj) standardGeneric("obj_name")) |
|
275 | ||
276 | ||
277 |
#' @rdname lab_name |
|
278 |
#' @export |
|
279 |
setGeneric("obj_name<-", function(obj, value) standardGeneric("obj_name<-")) |
|
280 |
# nocov end |
|
281 | ||
282 |
#' @seealso with_label |
|
283 |
#' @rdname lab_name |
|
284 |
#' @export |
|
285 | 3x |
setGeneric("obj_label", function(obj) standardGeneric("obj_label")) |
286 | ||
287 |
#' @rdname lab_name |
|
288 |
#' @param value character(1). The new label |
|
289 |
#' @export |
|
290 | 2x |
setGeneric("obj_label<-", function(obj, value) standardGeneric("obj_label<-")) |
291 | ||
292 |
#' @rdname lab_name |
|
293 |
#' @exportMethod obj_label |
|
294 | 3x |
setMethod("obj_label", "ANY", function(obj) attr(obj, "label")) |
295 | ||
296 |
#' @rdname lab_name |
|
297 |
#' @exportMethod obj_label<- |
|
298 |
setMethod( |
|
299 |
"obj_label<-", "ANY", |
|
300 |
function(obj, value) { |
|
301 | 2x |
attr(obj, "label") <- value |
302 | 2x |
obj |
303 |
} |
|
304 |
) |
|
305 | ||
306 |
#' @rdname lab_name |
|
307 |
#' @export |
|
308 | 133x |
setGeneric("obj_format", function(obj) standardGeneric("obj_format")) |
309 |
## this covers rcell, etc |
|
310 |
#' @rdname lab_name |
|
311 |
#' @exportMethod obj_format |
|
312 | 131x |
setMethod("obj_format", "ANY", function(obj) attr(obj, "format", exact = TRUE)) |
313 |
#' @rdname lab_name |
|
314 |
#' @export |
|
315 | 2x |
setMethod("obj_format", "fmt_config", function(obj) obj@format) |
316 | ||
317 |
#' @export |
|
318 |
#' @rdname lab_name |
|
319 | 3x |
setGeneric("obj_format<-", function(obj, value) standardGeneric("obj_format<-")) |
320 |
## this covers rcell, etc |
|
321 |
#' @exportMethod obj_format<- |
|
322 |
#' @rdname lab_name |
|
323 |
setMethod("obj_format<-", "ANY", function(obj, value) { |
|
324 | 2x |
attr(obj, "format") <- value |
325 | 2x |
obj |
326 |
}) |
|
327 |
#' @rdname lab_name |
|
328 |
#' @export |
|
329 |
setMethod("obj_format<-", "fmt_config", function(obj, value) { |
|
330 | 1x |
obj@format <- value |
331 | 1x |
obj |
332 |
}) |
|
333 | ||
334 |
#' @rdname lab_name |
|
335 |
#' @export |
|
336 | 3x |
setGeneric("obj_na_str", function(obj) standardGeneric("obj_na_str")) |
337 |
#' @rdname lab_name |
|
338 |
#' @exportMethod obj_na_str |
|
339 | 1x |
setMethod("obj_na_str", "ANY", function(obj) attr(obj, "format_na_str", exact = TRUE)) |
340 |
#' @rdname lab_name |
|
341 |
#' @export |
|
342 | 2x |
setMethod("obj_na_str", "fmt_config", function(obj) obj@format_na_str) |
343 | ||
344 |
#' @rdname lab_name |
|
345 |
#' @export |
|
346 | 2x |
setGeneric("obj_na_str<-", function(obj, value) standardGeneric("obj_na_str<-")) |
347 |
#' @exportMethod obj_na_str<- |
|
348 |
#' @rdname lab_name |
|
349 |
setMethod("obj_na_str<-", "ANY", function(obj, value) { |
|
350 | 1x |
attr(obj, "format_na_str") <- value |
351 | 1x |
obj |
352 |
}) |
|
353 |
#' @rdname lab_name |
|
354 |
#' @export |
|
355 |
setMethod("obj_na_str<-", "fmt_config", function(obj, value) { |
|
356 | 1x |
obj@format_na_str <- value |
357 | 1x |
obj |
358 |
}) |
|
359 | ||
360 |
#' @rdname lab_name |
|
361 |
#' @export |
|
362 | 3x |
setGeneric("obj_align", function(obj) standardGeneric("obj_align")) |
363 |
#' @rdname lab_name |
|
364 |
#' @exportMethod obj_align |
|
365 | 1x |
setMethod("obj_align", "ANY", function(obj) attr(obj, "align", exact = TRUE)) |
366 |
#' @rdname lab_name |
|
367 |
#' @export |
|
368 | 2x |
setMethod("obj_align", "fmt_config", function(obj) obj@align) |
369 | ||
370 |
#' @rdname lab_name |
|
371 |
#' @export |
|
372 | 2x |
setGeneric("obj_align<-", function(obj, value) standardGeneric("obj_align<-")) |
373 |
#' @exportMethod obj_align<- |
|
374 |
#' @rdname lab_name |
|
375 |
setMethod("obj_align<-", "ANY", function(obj, value) { |
|
376 | 1x |
attr(obj, "align") <- value |
377 | 1x |
obj |
378 |
}) |
|
379 |
#' @rdname lab_name |
|
380 |
#' @export |
|
381 |
setMethod("obj_align<-", "fmt_config", function(obj, value) { |
|
382 | 1x |
obj@align <- value |
383 | 1x |
obj |
384 |
}) |
|
385 | ||
386 |
#' General title/footer accessors |
|
387 |
#' |
|
388 |
#' @param obj ANY. Object to extract information from. |
|
389 |
#' @export |
|
390 |
#' @rdname title_footer |
|
391 |
#' @return A character scalar (`main_title`), a character vector (`main_footer`), or |
|
392 |
#' vector of length zero or more (`subtitles`, `page_titles`, |
|
393 |
#' `prov_footer`) containing the relevant title/footer contents |
|
394 | 92x |
setGeneric("main_title", function(obj) standardGeneric("main_title")) |
395 | ||
396 |
#' @export |
|
397 |
#' @rdname title_footer |
|
398 |
setMethod( |
|
399 |
"main_title", "MatrixPrintForm", |
|
400 | 92x |
function(obj) obj$main_title |
401 |
) |
|
402 | ||
403 |
##' @rdname title_footer |
|
404 |
##' @export |
|
405 | 6x |
setGeneric("main_title<-", function(obj, value) standardGeneric("main_title<-")) |
406 |
##' @rdname title_footer |
|
407 |
##' @export |
|
408 |
setMethod( |
|
409 |
"main_title<-", "MatrixPrintForm", |
|
410 |
function(obj, value) { |
|
411 | 6x |
obj$main_title <- value |
412 | 6x |
obj |
413 |
} |
|
414 |
) |
|
415 | ||
416 | ||
417 | ||
418 |
#' @export |
|
419 |
#' @rdname title_footer |
|
420 |
setGeneric("subtitles", function(obj) standardGeneric("subtitles")) ## nocov |
|
421 | ||
422 |
#' @export |
|
423 |
#' @rdname title_footer |
|
424 |
setMethod( |
|
425 |
"subtitles", "MatrixPrintForm", |
|
426 | 93x |
function(obj) obj$subtitles |
427 |
) |
|
428 | ||
429 |
##' @rdname title_footer |
|
430 |
##' @export |
|
431 |
setGeneric("subtitles<-", function(obj, value) standardGeneric("subtitles<-")) ## nocov |
|
432 | ||
433 |
##' @rdname title_footer |
|
434 |
##' @export |
|
435 |
setMethod( |
|
436 |
"subtitles<-", "MatrixPrintForm", |
|
437 |
function(obj, value) { |
|
438 | 5x |
obj$subtitles <- value |
439 | 5x |
obj |
440 |
} |
|
441 |
) |
|
442 | ||
443 |
#' @export |
|
444 |
#' @rdname title_footer |
|
445 | 109x |
setGeneric("page_titles", function(obj) standardGeneric("page_titles")) |
446 | ||
447 |
#' @export |
|
448 |
#' @rdname title_footer |
|
449 |
setMethod( |
|
450 |
"page_titles", "MatrixPrintForm", |
|
451 | 109x |
function(obj) obj$page_titles |
452 |
) |
|
453 |
#' @rdname title_footer |
|
454 |
#' @export |
|
455 | ! |
setMethod("page_titles", "ANY", function(obj) NULL) |
456 | ||
457 |
##' @rdname title_footer |
|
458 |
##' @export |
|
459 | 2x |
setGeneric("page_titles<-", function(obj, value) standardGeneric("page_titles<-")) |
460 | ||
461 |
#' @export |
|
462 |
#' @rdname title_footer |
|
463 |
setMethod( |
|
464 |
"page_titles<-", "MatrixPrintForm", |
|
465 |
function(obj, value) { |
|
466 | 2x |
if (!is.character(value)) { |
467 | ! |
stop("page titles must be in the form of a character vector, got object of class ", class(value)) |
468 |
} |
|
469 | 2x |
obj$page_titles <- value |
470 | 2x |
obj |
471 |
} |
|
472 |
) |
|
473 | ||
474 | ||
475 | ||
476 |
#' @export |
|
477 |
#' @rdname title_footer |
|
478 | 87x |
setGeneric("main_footer", function(obj) standardGeneric("main_footer")) |
479 | ||
480 |
#' @export |
|
481 |
#' @rdname title_footer |
|
482 |
setMethod( |
|
483 |
"main_footer", "MatrixPrintForm", |
|
484 | 87x |
function(obj) obj$main_footer |
485 |
) |
|
486 | ||
487 |
#' @rdname title_footer |
|
488 |
#' @param value character. New value. |
|
489 |
#' @export |
|
490 | 6x |
setGeneric("main_footer<-", function(obj, value) standardGeneric("main_footer<-")) |
491 | ||
492 | ||
493 | ||
494 |
#' @export |
|
495 |
#' @rdname title_footer |
|
496 |
setMethod( |
|
497 |
"main_footer<-", "MatrixPrintForm", |
|
498 |
function(obj, value) { |
|
499 | 6x |
if (!is.character(value)) { |
500 | ! |
stop("main footer must be a character vector. Got object of class ", class(value)) |
501 |
} |
|
502 | 6x |
obj$main_footer <- value |
503 | 6x |
obj |
504 |
} |
|
505 |
) |
|
506 | ||
507 | ||
508 |
#' @export |
|
509 |
#' @rdname title_footer |
|
510 | 97x |
setGeneric("prov_footer", function(obj) standardGeneric("prov_footer")) |
511 | ||
512 |
#' @export |
|
513 |
#' @rdname title_footer |
|
514 |
setMethod( |
|
515 |
"prov_footer", "MatrixPrintForm", |
|
516 | 97x |
function(obj) obj$prov_footer |
517 |
) |
|
518 | ||
519 |
#' @rdname title_footer |
|
520 |
#' @export |
|
521 | 7x |
setGeneric("prov_footer<-", function(obj, value) standardGeneric("prov_footer<-")) |
522 | ||
523 |
#' @export |
|
524 |
#' @rdname title_footer |
|
525 |
setMethod( |
|
526 |
"prov_footer<-", "MatrixPrintForm", |
|
527 |
function(obj, value) { |
|
528 | 7x |
if (!is.character(value)) { |
529 | ! |
stop("provenance footer must be a character vector. Got object of class ", class(value)) |
530 |
} |
|
531 | 7x |
obj$prov_footer <- value |
532 | 7x |
obj |
533 |
} |
|
534 |
) |
|
535 | ||
536 | ||
537 | ||
538 | ||
539 |
#' @rdname title_footer |
|
540 |
#' @export |
|
541 | 1x |
all_footers <- function(obj) c(main_footer(obj), prov_footer(obj)) |
542 | ||
543 |
#' @rdname title_footer |
|
544 |
#' @export |
|
545 | 90x |
all_titles <- function(obj) c(main_title(obj), subtitles(obj), page_titles(obj)) |
546 | ||
547 | ||
548 |
#' Access or (recursively) set table inset. |
|
549 |
#' |
|
550 |
#' Table inset is the amount of characters that the body of |
|
551 |
#' a table, referential footnotes, and main footer material |
|
552 |
#' are inset from the left-alignment of the titles and provenance |
|
553 |
#' footer materials. |
|
554 |
#' |
|
555 |
#' @param obj ANY. Object to get or (recursively if necessary) set |
|
556 |
#' table inset for. |
|
557 |
#' @param value character(1). String to use as new header/body separator. |
|
558 |
#' |
|
559 |
#' @return for `table_inset` the integer value that the table body |
|
560 |
#' (including column heading information and section dividers), |
|
561 |
#' referential footnotes, and main footer should be inset from the |
|
562 |
#' left alignment of the titles and provenance footers during rendering. |
|
563 |
#' For `table_inset<-`, the `obj`, with the new table_inset value |
|
564 |
#' applied recursively to it and all its subtables. |
|
565 |
#' |
|
566 |
#' @export |
|
567 | 193x |
setGeneric("table_inset", function(obj) standardGeneric("table_inset")) |
568 | ||
569 |
#' @rdname table_inset |
|
570 |
#' @export |
|
571 |
setMethod( |
|
572 |
"table_inset", "MatrixPrintForm", |
|
573 | 193x |
function(obj) obj$table_inset |
574 |
) |
|
575 | ||
576 | ||
577 |
#' @rdname table_inset |
|
578 |
#' @export |
|
579 | 4x |
setGeneric("table_inset<-", function(obj, value) standardGeneric("table_inset<-")) |
580 | ||
581 |
#' @rdname table_inset |
|
582 |
#' @export |
|
583 |
setMethod( |
|
584 |
"table_inset<-", "MatrixPrintForm", |
|
585 |
function(obj, value) { |
|
586 | 4x |
newval <- as.integer(value) |
587 | 4x |
if (is.na(newval) || newval < 0) { |
588 | 1x |
stop("Got invalid value for table_inset: ", newval) |
589 |
} |
|
590 | 3x |
obj$table_inset <- newval |
591 | 3x |
obj |
592 |
} |
|
593 |
) |
|
594 | ||
595 | ||
596 | ||
597 | ||
598 |
#' Generic for Performing "Forced Pagination" |
|
599 |
#' |
|
600 |
#' Forced pagination is pagination which happens regardless of |
|
601 |
#' position on page. The object is expected to have all information |
|
602 |
#' necessary to locate such page breaks, and the `do_forced_pag` |
|
603 |
#' method is expected to fully perform those paginations. |
|
604 |
#' |
|
605 |
#' @param obj The object to be paginated. |
|
606 |
#' |
|
607 |
#' The `ANY` method simply returns a list of length one, containing |
|
608 |
#' `obj`. |
|
609 |
#' |
|
610 |
#' @return a list of subobjects, which will be further paginated |
|
611 |
#' by the standard pagination algorithm. |
|
612 |
#' |
|
613 |
#' |
|
614 |
#' @export |
|
615 | 46x |
setGeneric("do_forced_paginate", function(obj) standardGeneric("do_forced_paginate")) |
616 | ||
617 |
#' @export |
|
618 |
#' @rdname do_forced_paginate |
|
619 | 43x |
setMethod("do_forced_paginate", "ANY", function(obj) list(obj)) |
620 | ||
621 |
#' Number of repeated columns |
|
622 |
#' |
|
623 |
#' When called on a table-like object using the formatters framework, |
|
624 |
#' this method should return the number of columns which are mandatorily |
|
625 |
#' repeated after each horizontal pagination. |
|
626 |
#' |
|
627 |
#' Absent a class-specific method, this function returns 0, indicating |
|
628 |
#' no always-repeated columns. |
|
629 |
#' |
|
630 |
#' @param obj ANY. A table-like object. |
|
631 |
#' @note This number \emph{does not include row labels}, the repetition |
|
632 |
#' of which is handled separately. |
|
633 |
#' |
|
634 |
#' @return an integer. |
|
635 |
#' @export |
|
636 |
#' @examples |
|
637 |
#' mpf <- basic_matrix_form(mtcars) |
|
638 |
#' num_rep_cols(mpf) |
|
639 | 25x |
setGeneric("num_rep_cols", function(obj) standardGeneric("num_rep_cols")) |
640 |
#' @export |
|
641 |
#' @rdname num_rep_cols |
|
642 | 25x |
setMethod("num_rep_cols", "ANY", function(obj) 0L) |
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 | 115x |
has_topleft <- mf_has_topleft(matform) |
16 | 115x |
strmat <- mf_strings(matform) |
17 | 115x |
frmmat <- mf_formats(matform) |
18 | 115x |
spamat <- mf_spans(matform) |
19 | 115x |
alimat <- mf_aligns(matform) |
20 | 115x |
nr_header <- mf_nrheader(matform) |
21 | 115x |
nl_inds_header <- seq(1, mf_nlheader(matform)) |
22 | 115x |
hdr_inds <- 1:nr_header |
23 | ||
24 |
# hack that is necessary only if bottom aligned |
|
25 | 115x |
topleft_has_nl_char <- FALSE |
26 | 115x |
if (has_topleft) { |
27 | 2x |
tl <- strmat[nl_inds_header, 1, drop = TRUE] |
28 | 2x |
strmat[nl_inds_header, 1] <- "" |
29 | 2x |
tl <- tl[nzchar(tl)] # we are not interested in initial "" but we cover initial \n |
30 | 2x |
topleft_has_nl_char <- any(grepl("\n", tl)) |
31 | 2x |
tl_to_add_back <- strsplit(paste0(tl, collapse = "\n"), split = "\n", fixed = TRUE)[[1]] |
32 | 2x |
how_many_nl <- length(tl_to_add_back) |
33 |
} |
|
34 | ||
35 |
# pre-proc in case of wrapping and \n |
|
36 | 115x |
line_grouping <- mf_lgrouping(matform) |
37 | 115x |
strmat <- .compress_mat(strmat, line_grouping, "nl") |
38 | 115x |
frmmat <- .compress_mat(frmmat, line_grouping, "unique") # never not unique |
39 | 115x |
spamat <- .compress_mat(spamat, line_grouping, "unique") |
40 | 115x |
alimat <- .compress_mat(alimat, line_grouping, "unique") |
41 | 115x |
line_grouping <- unique(line_grouping) |
42 | ||
43 |
# nlines detects if there is a newline character |
|
44 | 115x |
row_nlines <- apply(strmat, 1, function(x) max(vapply(x, nlines, 1L), 1L)) |
45 | ||
46 | 115x |
if (has_topleft && (sum(row_nlines[nl_inds_header]) < how_many_nl)) { |
47 | 1x |
row_nlines[1] <- row_nlines[1] + how_many_nl - sum(row_nlines[nl_inds_header]) |
48 |
} |
|
49 | ||
50 |
# There is something to change |
|
51 | 115x |
if (any(row_nlines > 1) || topleft_has_nl_char) { |
52 | ||
53 |
# False: Padder should be bottom aligned if no topleft (case of rlistings) |
|
54 |
# It is always bottom: tl_padder <- ifelse(has_topleft, pad_vert_top, pad_vert_bottom) |
|
55 | ||
56 | 12x |
newstrmat <- rbind( |
57 | 12x |
cbind( |
58 | 12x |
expand_mat_rows(strmat[hdr_inds, 1, drop = FALSE], |
59 | 12x |
row_nlines[hdr_inds], |
60 | 12x |
cpadder = pad_vert_bottom # topleft info is NOT top aligned |
61 |
), |
|
62 | 12x |
expand_mat_rows(strmat[hdr_inds, -1, drop = FALSE], |
63 | 12x |
row_nlines[hdr_inds], |
64 | 12x |
cpadder = pad_vert_bottom # colnames are bottom aligned |
65 |
) |
|
66 |
), |
|
67 | 12x |
expand_mat_rows(strmat[-1 * hdr_inds, , drop = FALSE], row_nlines[-hdr_inds]) |
68 |
) |
|
69 | ||
70 | 12x |
newfrmmat <- rbind( |
71 | 12x |
expand_mat_rows(frmmat[hdr_inds, , drop = FALSE], |
72 | 12x |
row_nlines[hdr_inds], |
73 | 12x |
cpadder = pad_vert_bottom), |
74 | 12x |
expand_mat_rows(frmmat[-1 * hdr_inds, , drop = FALSE], row_nlines[-hdr_inds]) |
75 |
) |
|
76 | ||
77 | 12x |
if (has_topleft) { |
78 | 2x |
starts_from_ind <- if (sum(row_nlines[hdr_inds]) - how_many_nl > 0){ |
79 | 1x |
sum(row_nlines[hdr_inds]) - how_many_nl |
80 |
} else { |
|
81 | 1x |
0 |
82 |
} |
|
83 | 2x |
newstrmat[starts_from_ind + seq_along(tl_to_add_back), 1] <- tl_to_add_back |
84 |
} |
|
85 | ||
86 | 12x |
mf_strings(matform) <- newstrmat |
87 | 12x |
mf_formats(matform) <- newfrmmat |
88 | 12x |
mf_spans(matform) <- expand_mat_rows(spamat, row_nlines, rep_vec_to_len) |
89 | 12x |
mf_aligns(matform) <- expand_mat_rows(alimat, row_nlines, rep_vec_to_len) |
90 |
## mf_display(matform) <- expand_mat_rows(mf_display(matform), row_nlines, rep_vec_to_len) |
|
91 | 12x |
mf_lgrouping(matform) <- rep(line_grouping, times = row_nlines) |
92 |
} |
|
93 | ||
94 | 115x |
matform |
95 |
} |
|
96 | ||
97 |
# Helper function to recompact the lines following line groupings to then have them expanded again |
|
98 |
.compress_mat <- function(mat, line_grouping, collapse_method = c("nl", "unique")) { |
|
99 | 460x |
list_compacted_mat <- lapply(unique(line_grouping), function(lg){ |
100 | 9524x |
apply(mat, 2, function(mat_cols) { |
101 | 79032x |
col_vec <- mat_cols[which(line_grouping == lg)] |
102 | 79032x |
if (collapse_method[1] == "nl") { |
103 | 19758x |
paste0(col_vec, collapse = "\n") |
104 |
} else { |
|
105 | 59274x |
val <- unique(col_vec) |
106 | 59274x |
val <- val[nzchar(val)] |
107 | 59274x |
if (length(val) > 1) { |
108 | 9524x |
stop("Problem in linegroupings! Some do not have the same values.") # nocov |
109 | 59274x |
} else if(length(val) < 1) { |
110 | 2962x |
val <- "" # Case in which it is only "" |
111 |
} |
|
112 | 59274x |
val[[1]] |
113 |
} |
|
114 |
}) |
|
115 |
}) |
|
116 | 460x |
do.call("rbind", list_compacted_mat) |
117 |
} |
|
118 | ||
119 |
disp_from_spans <- function(spans) { |
|
120 | ||
121 | 149x |
display <- matrix(rep(TRUE, length(spans)), ncol = ncol(spans)) |
122 | ||
123 | 149x |
print_cells_mat <- spans == 1L |
124 | 149x |
if (!all(print_cells_mat)) { |
125 | 1x |
display_rws <- lapply( |
126 | 1x |
seq_len(nrow(spans)), |
127 | 1x |
function(i) { |
128 | 2x |
print_cells <- print_cells_mat[i, ] |
129 | 2x |
row <- spans[i, ] |
130 |
## display <- t(apply(spans, 1, function(row) { |
|
131 |
## print_cells <- row == 1 |
|
132 | ||
133 | 2x |
if (!all(print_cells)) { |
134 |
## need to calculate which cell need to be printed |
|
135 | 1x |
print_cells <- spans_to_viscell(row) |
136 |
} |
|
137 | 2x |
print_cells |
138 |
} |
|
139 |
) |
|
140 | 1x |
display <- do.call(rbind, display_rws) |
141 |
} |
|
142 | 149x |
display |
143 |
} |
|
144 | ||
145 |
## constructor |
|
146 |
#' @title Matrix Print Form - Intermediate Representation for ASCII Table Printing |
|
147 |
#' |
|
148 |
#' @note The bare constructor for the `MatrixPrintForm` should generally |
|
149 |
#' only be called by `matrix_form` custom methods, and almost never from other code. |
|
150 |
#' |
|
151 |
#' @param strings character matrix. Matrix of formatted, ready to |
|
152 |
#' display strings organized as they will be positioned when |
|
153 |
#' rendered. Elements that span more than one column must be |
|
154 |
#' followed by the correct number of placeholders (typically |
|
155 |
#' either empty strings or repeats of the value). |
|
156 |
#' @param spans numeric matrix. Matrix of same dimension as |
|
157 |
#' \code{strings} giving the spanning information for each |
|
158 |
#' element. Must be repeated to match placeholders in |
|
159 |
#' \code{strings}. |
|
160 |
#' @param aligns character matrix. Matrix of same dimension as |
|
161 |
#' \code{strings} giving the text alignment information for each |
|
162 |
#' element. Must be repeated to match placeholders in |
|
163 |
#' \code{strings}. Must be a supported text alignment. See |
|
164 |
#' [decimal_align] allowed values. |
|
165 |
#' @param formats matrix. Matrix of same dimension |
|
166 |
#' as \code{strings} giving the text format information for |
|
167 |
#' each element. Must be repeated to match placeholders in |
|
168 |
#' \code{strings}. |
|
169 |
#' @param row_info data.frame. Data.frame with row-information |
|
170 |
#' necessary for pagination (XXX document exactly what that is). |
|
171 |
#' @param line_grouping integer. Sequence of integers indicating how |
|
172 |
#' print lines correspond to semantic rows in the object. |
|
173 |
#' Typically this should not be set manually unless |
|
174 |
#' `expact_newlines` is set to \code{FALSE}. |
|
175 |
#' @param ref_fnotes list. Referential footnote information if |
|
176 |
#' applicable. |
|
177 |
#' @param nlines_header numeric(1). Number of lines taken up by the |
|
178 |
#' values of the header (i.e. not including the divider). |
|
179 |
#' @param nrow_header numeric(1). Number of \emph{rows} corresponding |
|
180 |
#' to the header. |
|
181 |
#' @param has_topleft logical(1). Does the corresponding table have |
|
182 |
#' 'top left information' which should be treated differently when |
|
183 |
#' expanding newlines. Ignored if \code{expand_newlines} is |
|
184 |
#' \code{FALSE}. |
|
185 |
#' @param has_rowlabs logical(1). Do the matrices (\code{strings}, |
|
186 |
#' \code{spans}, \code{aligns}) each contain a column that |
|
187 |
#' corresponds with row labels (Rather than with table cell |
|
188 |
#' values). Defaults to \code{TRUE}. |
|
189 |
#' @param main_title character(1). Main title as a string. |
|
190 |
#' @param subtitles character. Subtitles, as a character vector. |
|
191 |
#' @param page_titles character. Page-specific titles, as a character |
|
192 |
#' vector. |
|
193 |
#' @param main_footer character(1). Main footer as a string. |
|
194 |
#' @param prov_footer character. Provenance footer information as a |
|
195 |
#' character vector. |
|
196 |
#' @param expand_newlines logical(1). Should the matrix form generated |
|
197 |
#' expand rows whose values contain newlines into multiple |
|
198 |
#' 'physical' rows (as they will appear when rendered into |
|
199 |
#' ASCII). Defaults to \code{TRUE} |
|
200 |
#' @param col_gap numeric(1). Space (in characters) between columns |
|
201 |
#' @param table_inset numeric(1). Table inset. See |
|
202 |
#' \code{\link{table_inset}} |
|
203 |
#' @param colwidths numeric. NULL, or a vector of column rendering widths. |
|
204 |
#' if non-NULL, must have length equal to `ncol(strings)` |
|
205 |
#' @param indent_size numeric(1). Number of spaces to be used per level of indent (if supported by |
|
206 |
#' the relevant method). Defaults to 2. |
|
207 |
#' @export |
|
208 |
#' @return An object of class `MatrixPrintForm`. Currently this is |
|
209 |
#' implemented as an S3 class inheriting from list with the following |
|
210 |
#' elements: |
|
211 |
#' \describe{ |
|
212 |
#' \item{\code{strings}}{see argument} |
|
213 |
#' \item{\code{spans}}{see argument} |
|
214 |
#' \item{\code{aligns}}{see argument} |
|
215 |
#' \item{\code{display}}{logical matrix of same dimension as `strings` |
|
216 |
#' that specifies whether an element in `strings` will be displayed |
|
217 |
#' when the table is rendered} |
|
218 |
#' \item{\code{formats}}{see argument} |
|
219 |
#' \item{\code{row_info}}{see argument} |
|
220 |
#' \item{\code{line_grouping}}{see argument} |
|
221 |
#' \item{\code{ref_footnotes}}{see argument} |
|
222 |
#' \item{\code{main_title}}{see argument} |
|
223 |
#' \item{\code{subtitles}}{see argument} |
|
224 |
#' \item{\code{page_titles}}{see argument} |
|
225 |
#' \item{\code{main_footer}}{see argument} |
|
226 |
#' \item{\code{prov_footer}}{see argument} |
|
227 |
#' \item{\code{col_gap}}{see argument} |
|
228 |
#' \item{\code{table_inset}}{see argument} |
|
229 |
#' } |
|
230 |
#' |
|
231 |
#' as well as the following attributes: |
|
232 |
#' \describe{ |
|
233 |
#' \item{\code{nlines_header}}{see argument} |
|
234 |
#' \item{\code{nrow_header}}{see argument} |
|
235 |
#' \item{\code{ncols}}{number of columns \emph{of the table}, not including |
|
236 |
#' any row names/row labels} |
|
237 |
#' } |
|
238 |
MatrixPrintForm <- function(strings = NULL, |
|
239 |
spans, |
|
240 |
aligns, |
|
241 |
formats, |
|
242 |
row_info, |
|
243 |
line_grouping = seq_len(NROW(strings)), |
|
244 |
ref_fnotes = list(), |
|
245 |
nlines_header, |
|
246 |
nrow_header, |
|
247 |
has_topleft = TRUE, |
|
248 |
has_rowlabs = has_topleft, |
|
249 |
expand_newlines = TRUE, |
|
250 |
main_title = "", |
|
251 |
subtitles = character(), |
|
252 |
page_titles = character(), |
|
253 |
main_footer = "", |
|
254 |
prov_footer = character(), |
|
255 |
col_gap = 3, |
|
256 |
table_inset = 0L, |
|
257 |
colwidths = NULL, |
|
258 |
indent_size = 2) { |
|
259 | 28x |
display <- disp_from_spans(spans) |
260 | ||
261 | 28x |
ncs <- if (has_rowlabs) ncol(strings) - 1 else ncol(strings) |
262 | 28x |
ret <- structure( |
263 | 28x |
list( |
264 | 28x |
strings = strings, |
265 | 28x |
spans = spans, |
266 | 28x |
aligns = aligns, |
267 | 28x |
display = display, |
268 | 28x |
formats = formats, |
269 | 28x |
row_info = row_info, |
270 | 28x |
line_grouping = line_grouping, |
271 | 28x |
ref_footnotes = ref_fnotes, |
272 | 28x |
main_title = main_title, |
273 | 28x |
subtitles = subtitles, |
274 | 28x |
page_titles = page_titles, |
275 | 28x |
main_footer = main_footer, |
276 | 28x |
prov_footer = prov_footer, |
277 | 28x |
col_gap = col_gap, |
278 | 28x |
table_inset = as.integer(table_inset), |
279 | 28x |
has_topleft = has_topleft, |
280 | 28x |
indent_size = indent_size, |
281 | 28x |
col_widths = colwidths |
282 |
), |
|
283 | 28x |
nrow_header = nrow_header, |
284 | 28x |
ncols = ncs, |
285 | 28x |
class = c("MatrixPrintForm", "list") |
286 |
) |
|
287 | ||
288 |
## .do_mat_expand(ret) |
|
289 | 28x |
if (expand_newlines) { |
290 | 28x |
ret <- mform_handle_newlines(ret) |
291 |
} |
|
292 | ||
293 | ||
294 |
## ret <- shove_refdf_into_rowinfo(ret) |
|
295 | 28x |
if(is.null(colwidths)) |
296 | 28x |
colwidths <- propose_column_widths(ret) |
297 | 28x |
mf_col_widths(ret) <- colwidths |
298 | 28x |
ret <- mform_build_refdf(ret) |
299 | 28x |
ret |
300 |
} |
|
301 | ||
302 | ||
303 |
#'Create a row for a referential footnote information dataframe |
|
304 |
#' |
|
305 |
#' @inheritParams nlines |
|
306 |
#' @param row_path character. row path (`NA_character_` for none) |
|
307 |
#' @param col_path character. column path (`NA_character_` for none) |
|
308 |
#' @param row integer(1). Integer position of the row. |
|
309 |
#' @param col integer(1). Integer position of the column. |
|
310 |
#' @param symbol character(1). Symbol for the reference. `NA_character_` to use the `ref_index` automatically. |
|
311 |
#' @param ref_index integer(1). The index of the footnote, used for ordering even when symbol is not NA |
|
312 |
#' @param msg character(1). The string message, not including the symbol portion (`{symbol} - `) |
|
313 |
#' |
|
314 |
#' @return a single row data.frame with the appropriate columns. |
|
315 |
#' |
|
316 |
#' @export |
|
317 |
#' |
|
318 |
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) { |
|
319 | 3442x |
nlines <- nlines(msg, max_width = max_width) |
320 | 3442x |
data.frame(row_path = I(list(row_path)), |
321 | 3442x |
col_path = I(list(col_path)), |
322 | 3442x |
row = row, |
323 | 3442x |
col = col, |
324 | 3442x |
symbol = symbol, |
325 | 3442x |
ref_index = ref_index, |
326 | 3442x |
msg = msg, |
327 | 3442x |
nlines = nlines, |
328 | 3442x |
stringsAsFactors = FALSE) |
329 |
} |
|
330 | ||
331 | ||
332 |
## this entire thing is a hatchetjob of a hack which should not be necessary. |
|
333 |
## mf_rinfo(mform) should have the relevant info in it and |
|
334 |
## mf_cinfo(mform) should be non-null (!!!) and have the info in it |
|
335 |
## in which case this becomes silly and dumb, but here we are, so here we go. |
|
336 |
infer_ref_info <- function(mform, colspace_only) { |
|
337 | 112x |
if(colspace_only) |
338 | 56x |
idx <- seq_len(mf_nlheader(mform)) |
339 |
else |
|
340 | 56x |
idx <- seq_len(nrow(mf_strings(mform))) |
341 | ||
342 | ||
343 | 112x |
hasrlbs <- mf_has_rlabels(mform) |
344 | ||
345 | 112x |
strs <- mf_strings(mform)[idx, , drop = FALSE] |
346 | ||
347 |
## they're nested so \\2 is the inner one, without the brackets |
|
348 | 112x |
refs <- gsub("^[^{]*([{]([^}]+)[}]){0,1}$", "\\2", strs) |
349 |
## handle spanned values |
|
350 | 112x |
refs[!mf_display(mform)[idx,]] <- "" |
351 | ||
352 |
## we want to count across rows first, not down columns, cause |
|
353 |
## thats how footnote numbering works |
|
354 | 112x |
refs_inorder <- as.vector(t(refs)) |
355 | 112x |
keepem <- nzchar(refs_inorder) |
356 | 112x |
if(sum(keepem) == 0) |
357 | 110x |
return(ref_df_row()[0,]) |
358 | ||
359 | 2x |
refs_spl <- strsplit(refs_inorder[keepem], ", ", fixed = TRUE) |
360 | 2x |
runvec <- vapply(refs_spl, length, 1L) |
361 | ||
362 | ||
363 | ||
364 | 2x |
row_index <- as.vector(t(do.call(cbind, replicate(ncol(strs), |
365 | 2x |
list(mf_lgrouping(mform)[idx] - mf_nlheader(mform))))))[keepem] |
366 | 2x |
row_index[row_index < 1] <- NA_integer_ |
367 | 2x |
c_torep <- if(hasrlbs) c(NA_integer_, seq(1, ncol(strs) - 1)) else seq_len(ncol(strs)) |
368 | 2x |
col_index <- rep(c_torep, nrow(strs))[keepem] |
369 | ||
370 | ||
371 | ||
372 | ||
373 | 2x |
ret <- data.frame(symbol = unlist(refs_spl), |
374 | 2x |
row_path = I(mf_rinfo(mform)$path[rep(row_index, times = runvec)]), |
375 | 2x |
row = rep(row_index, times = runvec), |
376 | 2x |
col = rep(col_index, times = runvec)) |
377 | 2x |
ret$msg <- vapply(ret$symbol, function(sym) { |
378 | 16x |
fullmsg <- unique(grep(paste0("{",sym, "}"), fixed = TRUE, mf_rfnotes(mform), value = TRUE)) |
379 | 16x |
gsub("^[{][^}]+[}] - ", "", fullmsg) |
380 |
}, "") |
|
381 | ||
382 | ||
383 | 2x |
col_pths <- mf_col_paths(mform) |
384 | 2x |
ret$col_path <- replicate(nrow(ret), list(NA_character_)) |
385 | 2x |
non_na_col <- !is.na(ret$col) |
386 | 2x |
ret$col_path[non_na_col] <- col_pths[ret$col[non_na_col]] |
387 | 2x |
ret$ref_index <- seq_len(nrow(ret)) |
388 |
## |
|
389 | 2x |
ret$nlines <- vapply(paste0("{", ret$symbol, "} - ", ret$msg), nlines, 1L) |
390 | 2x |
ret <- ret[,names(ref_df_row())] |
391 | 2x |
ret |
392 |
} |
|
393 | ||
394 |
mform_build_refdf <- function(mform) { |
|
395 | 56x |
rdf <- mf_rinfo(mform) |
396 | 56x |
cref_rows <- infer_ref_info(mform, colspace_only = TRUE) |
397 |
## this will recheck sometimes but its safer and shouldn't |
|
398 |
## be too prohibitively costly |
|
399 | 56x |
if(NROW(rdf$ref_info_df) > 0 && sum(sapply(rdf$ref_info_df, NROW)) > 0) { |
400 | ! |
cref_rows <- infer_ref_info(mform, colspace_only = TRUE) |
401 | ! |
rref_rows <- rdf$ref_info_df |
402 |
} else { |
|
403 | 56x |
cref_rows <- infer_ref_info(mform, colspace_only = FALSE) |
404 | 56x |
rref_rows <- list() |
405 |
} |
|
406 | 56x |
mf_fnote_df(mform) <- do.call(rbind.data.frame, c(list(cref_rows), rref_rows)) |
407 | 56x |
update_mf_nlines(mform, colwidths = mf_col_widths(mform), max_width = NULL) |
408 |
} |
|
409 | ||
410 | ||
411 | ||
412 | ||
413 | ||
414 | ||
415 | ||
416 | ||
417 | ||
418 |
## constructor with snake_case naming convention |
|
419 |
#' @rdname MatrixPrintForm |
|
420 |
#' @export |
|
421 |
matrix_print_form <- MatrixPrintForm |
|
422 | ||
423 | ||
424 |
## hide the implementation behind abstraction in case we decide we want a real class someday |
|
425 |
#' `Setters` and `getters` for aspects of `MatrixPrintForm` Objects |
|
426 |
#' |
|
427 |
#' Most of these functions, particularly the `settters`, are intended |
|
428 |
#' almost exclusively for internal use in, e.g., `matrix_form` methods, |
|
429 |
#' and should generally not be called by end users. |
|
430 |
#' |
|
431 |
#' @param mf `MatrixPrintForm(1)`. A `MatrixPrintForm` object |
|
432 |
#' @param value ANY. The new value for the component in question. |
|
433 |
#' @return The element of the `MatrixPrintForm` associated with the `getter`, or |
|
434 |
#' the modified `MatrixPrintForm` object in the case of a `setter`. |
|
435 |
#' @export |
|
436 |
#' @rdname mpf_accessors |
|
437 | 1807x |
mf_strings <- function(mf) mf$strings |
438 | ||
439 |
#' @export |
|
440 |
#' @rdname mpf_accessors |
|
441 | ||
442 | 294x |
mf_spans <- function(mf) mf$spans |
443 |
#' @export |
|
444 |
#' @rdname mpf_accessors |
|
445 | ||
446 | 433x |
mf_aligns <- function(mf) mf$aligns |
447 | ||
448 |
#' @export |
|
449 |
#' @rdname mpf_accessors |
|
450 | 241x |
mf_display <- function(mf) mf$display |
451 | ||
452 |
#' @export |
|
453 |
#' @rdname mpf_accessors |
|
454 | 224x |
mf_formats <- function(mf) mf$formats |
455 | ||
456 |
#' @export |
|
457 |
#' @rdname mpf_accessors |
|
458 | 1400x |
mf_rinfo <- function(mf) mf$row_info |
459 | ||
460 |
#' @export |
|
461 |
#' @rdname mpf_accessors |
|
462 | 78x |
mf_cinfo <- function(mf) mf$col_info |
463 | ||
464 | ||
465 |
#' @export |
|
466 |
#' @rdname mpf_accessors |
|
467 | 117x |
mf_has_topleft <- function(mf) mf$has_topleft |
468 | ||
469 |
#' @export |
|
470 |
#' @rdname mpf_accessors |
|
471 | 2364x |
mf_lgrouping <- function(mf) mf$line_grouping |
472 | ||
473 |
#' @export |
|
474 |
#' @rdname mpf_accessors |
|
475 | 77x |
mf_rfnotes <- function(mf) mf$ref_footnotes |
476 | ||
477 |
#' @export |
|
478 |
#' @rdname mpf_accessors |
|
479 | 1068x |
mf_nlheader <- function(mf) sum(mf_lgrouping(mf) <= mf_nrheader(mf)) |
480 | ||
481 |
#' @export |
|
482 |
#' @rdname mpf_accessors |
|
483 | 1889x |
mf_nrheader <- function(mf) attr(mf, "nrow_header", exact = TRUE) |
484 | ||
485 | ||
486 |
#' @export |
|
487 |
#' @rdname mpf_accessors |
|
488 | 149x |
mf_colgap <- function(mf) mf$col_gap |
489 | ||
490 | ||
491 | ||
492 | ||
493 |
## XXX should this be exported? not sure if there's a point |
|
494 |
mf_col_paths <- function(mf) { |
|
495 | 2x |
if(!is.null(mf_cinfo(mf))) |
496 | ! |
mf_cinfo(mf)$path |
497 |
else |
|
498 | 2x |
as.list(paste0("col", seq_len(nrow(mf_strings(mf)) - mf_has_topleft(mf)))) |
499 |
} |
|
500 | ||
501 | ||
502 |
mf_col_widths <- function(mf) { |
|
503 | 200x |
mf$col_widths |
504 |
} |
|
505 | ||
506 |
`mf_col_widths<-` <- function(mf, value) { |
|
507 | 157x |
if(!is.null(value) && length(value) != NCOL(mf_strings(mf))) |
508 | ! |
stop("Number of column widths (", length(value), ") does not match ", |
509 | ! |
"number of columns in strings matrix (", NCOL(mf_strings(mf)), ").") |
510 | 157x |
mf$col_widths <- value |
511 | 157x |
mf |
512 |
} |
|
513 | ||
514 |
mf_fnote_df <- function(mf) { |
|
515 | 703x |
mf$ref_fnote_df |
516 |
} |
|
517 | ||
518 |
`mf_fnote_df<-` <- function(mf, value) { |
|
519 | 192x |
stopifnot(is.null(value) || ( |
520 | 192x |
is.data.frame(value) && identical(names(value), names(ref_df_row())))) |
521 | 192x |
mf$ref_fnote_df <- value |
522 | 192x |
mf |
523 |
} |
|
524 | ||
525 | ||
526 |
splice_fnote_info_in <- function(df, refdf, row = TRUE) { |
|
527 | 182x |
if(NROW(df) == 0) |
528 | ! |
return(df) |
529 | ||
530 | 182x |
colnm <- ifelse(row, "row", "col") |
531 | 182x |
refdf <- refdf[!is.na(refdf[[colnm]]),] |
532 | ||
533 | 182x |
refdf_spl <- split(refdf, refdf[[colnm]]) |
534 | 182x |
df$ref_info_df <- replicate(nrow(df), list(ref_df_row()[0,])) |
535 | 182x |
df$ref_info_df[as.integer(names(refdf_spl))] <- refdf_spl |
536 | 182x |
df |
537 |
} |
|
538 | ||
539 | ||
540 |
shove_refdf_into_rowinfo <- function(mform) { |
|
541 | 136x |
refdf <- mf_fnote_df(mform) |
542 | 136x |
rowinfo <- mf_rinfo(mform) |
543 | 136x |
mf_rinfo(mform) <- splice_fnote_info_in(rowinfo, refdf) |
544 | 136x |
mform |
545 |
} |
|
546 | ||
547 |
update_mf_nlines <- function(mform, colwidths, max_width) { |
|
548 | 141x |
mform <- update_mf_ref_nlines(mform, max_width = max_width) |
549 | 141x |
mform <- update_mf_rinfo_extents(mform) |
550 | ||
551 | 141x |
mform |
552 |
} |
|
553 | ||
554 |
update_mf_rinfo_extents <- function(mform) { |
|
555 | 141x |
rinfo <- mf_rinfo(mform) |
556 | 141x |
refdf_all <- mf_fnote_df(mform) |
557 | 141x |
refdf_rows <- refdf_all[!is.na(refdf_all$row),] |
558 | 141x |
if(NROW(rinfo) == 0) |
559 | ! |
return(mform) |
560 | 141x |
lgrp <- mf_lgrouping(mform) - mf_nrheader(mform) |
561 | 141x |
lgrp <- lgrp[lgrp > 0] |
562 | 141x |
rf_nlines <- vapply(seq_len(max(lgrp)), function(ii) { |
563 | ||
564 | 2940x |
refdfii <- refdf_rows[refdf_rows$row == ii,] |
565 | 2940x |
refdfii <- refdfii[!duplicated(refdfii$symbol), ] |
566 | 2940x |
if(NROW(refdfii) == 0L) |
567 | 2844x |
return(0L) |
568 | 96x |
sum(refdfii$nlines) |
569 | 141x |
}, 1L) |
570 | ||
571 | 141x |
raw_self_exts <- vapply(split(lgrp, lgrp), length, 0L) |
572 | 141x |
stopifnot(length(raw_self_exts) == length(rf_nlines)) |
573 | 141x |
new_exts <- raw_self_exts + rf_nlines |
574 | ||
575 | 141x |
mapdf <- data.frame(row_num = as.integer(names(new_exts)), |
576 | 141x |
raw_extent = raw_self_exts) |
577 | 141x |
stopifnot(all(mapdf$row_num == rinfo$abs_rownumber)) |
578 | ||
579 | ||
580 | 141x |
new_par_exts <- vapply(rinfo$reprint_inds, |
581 | 141x |
function(idx) { |
582 | 2940x |
sum(0L, mapdf$raw_extent[mapdf$row_num %in% idx]) |
583 | 141x |
}, 1L) |
584 | ||
585 | 141x |
rinfo$self_extent <- new_exts |
586 | 141x |
rinfo$par_extent <- new_par_exts |
587 | 141x |
rinfo$nreflines <- rf_nlines |
588 | 141x |
mf_rinfo(mform) <- rinfo |
589 | 141x |
mform |
590 |
} |
|
591 | ||
592 |
update_mf_ref_nlines <- function(mform, max_width) { |
|
593 | 141x |
refdf <- mf_fnote_df(mform) |
594 | 141x |
if(NROW(refdf) == 0) |
595 | 114x |
return(mform) |
596 | ||
597 | 27x |
refdf$nlines <- vapply(paste0("{", refdf$symbol, "} - ", refdf$msg), |
598 | 27x |
nlines, |
599 | 27x |
max_width = max_width, |
600 | 27x |
1L) |
601 | 27x |
mf_fnote_df(mform) <- refdf |
602 | 27x |
shove_refdf_into_rowinfo(mform) |
603 |
} |
|
604 | ||
605 | ||
606 | ||
607 |
#' @export |
|
608 |
#' @rdname mpf_accessors |
|
609 |
`mf_strings<-` <- function(mf, value) { |
|
610 | 294x |
mf$strings <- value |
611 | 294x |
mf |
612 |
} |
|
613 | ||
614 |
.chkdim_and_replace <- function(mf, value, component) { |
|
615 | 378x |
strdim <- dim(mf_strings(mf)) |
616 | 378x |
vdim <- dim(value) |
617 | 378x |
if (!is.null(strdim) && !identical(strdim, vdim)) { |
618 | 1x |
stop( |
619 | 1x |
"Dimensions of new '", component, "' value (", |
620 | 1x |
vdim[1], ", ", vdim[2], # nocov |
621 | 1x |
") do not match dimensions of existing 'strings' component (", # nocov |
622 | 1x |
strdim[1], ", ", strdim[2], ")." # nocov |
623 |
) |
|
624 |
} |
|
625 | 377x |
mf[[component]] <- value |
626 | 377x |
mf |
627 |
} |
|
628 | ||
629 | ||
630 |
#' @export |
|
631 |
#' @rdname mpf_accessors |
|
632 |
`mf_spans<-` <- function(mf, value) { |
|
633 | 122x |
mf <- .chkdim_and_replace(mf, value, component = "spans") |
634 | 121x |
mf$display <- disp_from_spans(value) |
635 | 121x |
mf |
636 |
} |
|
637 | ||
638 |
#' @export |
|
639 |
#' @rdname mpf_accessors |
|
640 |
`mf_aligns<-` <- function(mf, value) { |
|
641 | 135x |
.chkdim_and_replace(mf, value, component = "aligns") |
642 |
} |
|
643 | ||
644 | ||
645 |
#' @export |
|
646 |
#' @rdname mpf_accessors |
|
647 |
`mf_display<-` <- function(mf, value) { |
|
648 | ! |
stop("display is now a derived element of the matrix print form, modify it via `mf_spans<-`") |
649 | ! |
.chkdim_and_replace(mf, value, component = "display") |
650 |
} |
|
651 | ||
652 |
#' @export |
|
653 |
#' @rdname mpf_accessors |
|
654 |
`mf_formats<-` <- function(mf, value) { |
|
655 | 121x |
.chkdim_and_replace(mf, value, component = "formats") |
656 |
} |
|
657 | ||
658 | ||
659 |
## NB NROW(v) == length(v) for atomic vectors so this is ok for lgrouping as wellas rinfo |
|
660 |
.chknrow_and_replace <- function(mf, value, component, noheader = FALSE) { |
|
661 | 121x |
strdim <- NROW(mf_strings(mf)) - if (noheader) mf_nlheader(mf) else 0L |
662 | 121x |
vdim <- NROW(value) |
663 | 121x |
if (!is.null(strdim) && !identical(strdim, vdim)) { |
664 | ! |
stop( |
665 | ! |
"Number of rows/length of new '", component, "' value (", |
666 | ! |
vdim[1], |
667 | ! |
") does not match existing 'strings' component (", |
668 | ! |
strdim[1], ")." |
669 |
) |
|
670 |
} |
|
671 | 121x |
mf[[component]] <- value |
672 | 121x |
mf |
673 |
} |
|
674 | ||
675 |
#' @export |
|
676 |
#' @rdname mpf_accessors |
|
677 |
`mf_rinfo<-` <- function(mf, value) { |
|
678 |
## this can someijtmes be called after expanding newlines so in general |
|
679 |
## we should not expect it to match the number of rows in the strings matrix |
|
680 |
##.chknrow_and_replace(mf, value, component = "row_info", noheader = TRUE) |
|
681 | 324x |
lgrps <- mf_lgrouping(mf) |
682 | 324x |
nrs <- length(unique(lgrps[-seq_len(mf_nlheader(mf))])) |
683 | 324x |
if(NROW(value) != nrs) |
684 | 1x |
stop("Rows in new row_info component (", |
685 | 1x |
NROW(value), |
686 | 1x |
") does not match number of rows reflected in line_grouping component (", |
687 | 1x |
nrs, ")") |
688 | 323x |
mf$row_info <- value |
689 | 323x |
mf |
690 |
} |
|
691 | ||
692 |
#' @export |
|
693 |
#' @rdname mpf_accessors |
|
694 |
`mf_cinfo<-` <- function(mf, value) { |
|
695 | 46x |
if(NROW(value) > 0 && NROW(value) != ncol(mf)) |
696 | ! |
stop("Number of rows in new cinfo (", NROW(value), ") does not match ", |
697 | ! |
"number of columns (", ncol(mf), ")") |
698 | 46x |
mf$col_info <- value |
699 | 46x |
mf |
700 |
} |
|
701 | ||
702 | ||
703 |
#' @export |
|
704 |
#' @rdname mpf_accessors |
|
705 |
`mf_lgrouping<-` <- function(mf, value) { |
|
706 | 121x |
.chknrow_and_replace(mf, value, component = "line_grouping") |
707 |
} |
|
708 | ||
709 | ||
710 |
#' @export |
|
711 |
#' @rdname mpf_accessors |
|
712 |
`mf_rfnotes<-` <- function(mf, value) { |
|
713 | 114x |
mf$ref_footnotes <- value |
714 | 114x |
mf |
715 |
} |
|
716 | ||
717 | ||
718 | ||
719 |
#' @export |
|
720 |
#' @rdname mpf_accessors |
|
721 |
`mf_nrheader<-` <- function(mf, value) { |
|
722 | 2x |
attr(mf, "nrow_header") <- value |
723 | 2x |
mf |
724 |
} |
|
725 | ||
726 |
#' @export |
|
727 |
#' @rdname mpf_accessors |
|
728 |
`mf_colgap<-` <- function(mf, value) { |
|
729 | ! |
mf$col_gap <- value |
730 | ! |
mf |
731 |
} |
|
732 | ||
733 |
#' @export |
|
734 |
#' @rdname mpf_accessors |
|
735 | 479x |
mf_ncol <- function(mf) attr(mf, "ncols", exact = TRUE) |
736 | ||
737 |
#' @export |
|
738 |
#' @rdname mpf_accessors |
|
739 | 10x |
mf_nrow <- function(mf) max(mf_lgrouping(mf)) - mf_nrheader(mf) |
740 | ||
741 | ||
742 | ||
743 |
#' @export |
|
744 |
#' @rdname mpf_accessors |
|
745 |
`mf_ncol<-` <- function(mf, value) { |
|
746 | 136x |
stopifnot(is.numeric(value)) |
747 | 136x |
attr(mf, "ncols") <- value |
748 | 136x |
mf |
749 |
} |
|
750 | ||
751 |
#' @param x `MatrixPrintForm`. The object. |
|
752 |
#' @export |
|
753 |
#' @rdname mpf_accessors |
|
754 |
setMethod( |
|
755 |
"ncol", "MatrixPrintForm", |
|
756 | 478x |
function(x) mf_ncol(x) |
757 |
) |
|
758 | ||
759 |
#' @export |
|
760 |
#' @rdname mpf_accessors |
|
761 |
mpf_has_rlabels <- function(mf) { |
|
762 | ! |
.Deprecated("mf_has_rlabels") |
763 | ! |
mf_has_rlabels(mf) |
764 |
} |
|
765 | ||
766 |
#' @export |
|
767 |
#' @rdname mpf_accessors |
|
768 | 243x |
mf_has_rlabels <- function(mf) ncol(mf$strings) > ncol(mf) |
769 | ||
770 |
#' Create spoof matrix form from a data.frame |
|
771 |
#' |
|
772 |
#' This is useful primarily for writing testing/examples, and as a |
|
773 |
#' starting point for more sophisticated custom `matrix_form` methods |
|
774 |
#' |
|
775 |
#' @param df data.frame |
|
776 |
#' @param parent_path character. parent path that all rows should be "children of", |
|
777 |
#' defaults to `"root"`, and generally should not matter to end users. |
|
778 |
#' |
|
779 |
#' @return A valid `MatrixPrintForm` object representing `df`, |
|
780 |
#' ready for ASCII rendering |
|
781 |
#' |
|
782 |
#' @examples |
|
783 |
#' mform <- basic_matrix_form(mtcars) |
|
784 |
#' cat(toString(mform)) |
|
785 |
#' @export |
|
786 |
basic_matrix_form <- function(df, parent_path = "root") { |
|
787 | 26x |
fmts <- lapply(df, function(x) if (is.null(obj_format(x))) "xx" else obj_format(x)) |
788 | ||
789 | 26x |
bodystrs <- mapply(function(x, fmt) { |
790 | 129x |
sapply(x, format_value, format = fmt) |
791 | 26x |
}, x = df, fmt = fmts) |
792 | ||
793 | 26x |
rnms <- row.names(df) |
794 | 26x |
if (is.null(rnms)) { |
795 | ! |
rnms <- as.character(seq_len(NROW(df))) |
796 |
} |
|
797 | ||
798 | 26x |
cnms <- names(df) |
799 | ||
800 | 26x |
strings <- rbind( |
801 | 26x |
c("", cnms), |
802 | 26x |
cbind(rnms, bodystrs) |
803 |
) |
|
804 | ||
805 | 26x |
fnr <- nrow(strings) |
806 | 26x |
fnc <- ncol(strings) |
807 | ||
808 |
## center alignment for column labels, left alignment for everything else |
|
809 | 26x |
aligns <- rbind( |
810 | 26x |
"center", |
811 | 26x |
matrix("left", nrow = NROW(df), ncol = fnc) |
812 |
) |
|
813 | ||
814 | ||
815 |
## build up fake pagination df |
|
816 | 26x |
charcols <- which(sapply(df, is.character)) |
817 | 26x |
if (length(charcols) > 0) { |
818 | 1x |
exts <- apply(df[, charcols, drop = FALSE], 1, function(x) max(vapply(x, nlines, 1L))) |
819 |
} else { |
|
820 | 25x |
exts <- rep(1L, NROW(df)) |
821 |
} |
|
822 | 26x |
rowdf <- basic_pagdf(row.names(df), |
823 | 26x |
extents = exts, |
824 | 26x |
parent_path = parent_path |
825 |
) |
|
826 | 26x |
formats <- cbind( |
827 |
"", |
|
828 | 26x |
rbind( |
829 |
"", |
|
830 | 26x |
matrix("xx", nrow = nrow(df), ncol = ncol(df)) |
831 |
) |
|
832 |
) |
|
833 | ||
834 | 26x |
ret <- matrix_print_form( |
835 | 26x |
strings = strings, |
836 | 26x |
aligns = aligns, |
837 | 26x |
spans = matrix(1, nrow = fnr, ncol = fnc), |
838 | 26x |
formats = formats, ## matrix("xx", nrow = fnr, ncol = fnc), |
839 | 26x |
row_info = rowdf, |
840 | 26x |
has_topleft = FALSE, |
841 | 26x |
nlines_header = 1, |
842 | 26x |
nrow_header = 1, |
843 | 26x |
has_rowlabs = TRUE |
844 |
) |
|
845 | 26x |
mform_build_refdf(ret) |
846 |
} |
|
847 | ||
848 | ||
849 |
map_to_new <- function(old, map) { |
|
850 | 150x |
inds <- match(old, map$old_idx) |
851 | 150x |
map$new_idx[inds] |
852 | ||
853 |
} |
|
854 | ||
855 | ||
856 |
reconstruct_basic_fnote_list <- function(mf) { |
|
857 | 111x |
refdf <- mf_fnote_df(mf) |
858 | 111x |
if(NROW(refdf) == 0) |
859 | 71x |
return(NULL) |
860 | 40x |
refdf <- refdf[!duplicated(refdf$symbol),] |
861 | 40x |
paste0("{", refdf$symbol, "} - ", refdf$msg) |
862 |
} |
|
863 | ||
864 | ||
865 |
fix_fnote_df <- function(df) { |
|
866 | 41x |
ind_symb <- df$symbol == as.character(df$ref_index) |
867 | 41x |
df$ref_index <- seq_len(nrow(df)) |
868 | 41x |
df$symbol[ind_symb] <- as.character(df$ref_index[ind_symb]) |
869 | 41x |
df |
870 |
} |
|
871 | ||
872 | ||
873 | ||
874 | ||
875 | ||
876 | ||
877 | ||
878 |
.mf_subset_core_mats <- function(mf, i, row = TRUE) { |
|
879 | 109x |
fillnum <- if(row) nrow(mf_strings(mf)) - mf_nlheader(mf) else ncol(mf) |
880 | 109x |
if(is.logical(i) || all(i < 0)) |
881 | ! |
i <- seq_len(fillnum)[i] |
882 | ||
883 | 109x |
if(row) { |
884 | 41x |
nlh <- mf_nlheader(mf) |
885 | 41x |
ncolrows <- mf_nrheader(mf) |
886 | 41x |
i_mat <- c(seq_len(nlh), which(mf_lgrouping(mf) %in% (i + ncolrows))) |
887 | 41x |
j_mat <- seq_len(ncol(mf_strings(mf))) |
888 |
} else { |
|
889 | 68x |
nlabcol <- as.integer(mf_has_rlabels(mf)) |
890 | 68x |
i_mat <- seq_len(nrow(mf_strings(mf))) |
891 | 68x |
j_mat <- c(seq_len(nlabcol), i + nlabcol) |
892 |
} |
|
893 | ||
894 | ||
895 | 109x |
mf_strings(mf) <- mf_strings(mf)[i_mat, j_mat, drop = FALSE] |
896 | 109x |
mf_lgrouping(mf) <- as.integer(as.factor(mf_lgrouping(mf)[i_mat])) |
897 | 109x |
if(!row) |
898 | 68x |
newspans <- truncate_spans(mf_spans(mf), j_mat) #'i' is the columns here, b/c row is FALSE |
899 |
else |
|
900 | 41x |
newspans <- mf_spans(mf)[i_mat, j_mat, drop = FALSE] |
901 | 109x |
mf_spans(mf) <- newspans |
902 | 109x |
mf_formats(mf) <- mf_formats(mf)[i_mat, j_mat, drop = FALSE] |
903 | ||
904 | 109x |
mf_aligns(mf) <- mf_aligns(mf)[i_mat, j_mat, drop = FALSE] |
905 | 109x |
if(!row) { |
906 | 68x |
mf_ncol(mf) <- length(i) |
907 | 68x |
if(!is.null(mf_col_widths(mf))) |
908 | 68x |
mf_col_widths(mf) <- mf_col_widths(mf)[j_mat] |
909 |
} |
|
910 | 109x |
mf |
911 |
} |
|
912 | ||
913 |
## ugh. spans are **way** more of a pain than I expected x.x |
|
914 |
truncate_one_span <- function(spanrow, j) { |
|
915 | 1956x |
i <- 1 |
916 | 1956x |
len <- length(spanrow) |
917 | 1956x |
while(i < len) { |
918 | 22365x |
spnlen <- spanrow[i] |
919 | 22365x |
inds <- seq(i, i + spnlen - 1) |
920 | 22365x |
newspnlen <- sum(inds %in% j) |
921 | 22365x |
spanrow[inds] <- newspnlen |
922 | 22365x |
i <- i + spnlen |
923 |
} |
|
924 | 1956x |
spanrow[j] |
925 |
} |
|
926 | ||
927 |
truncate_spans <- function(spans, j) { |
|
928 | 68x |
if (length(spans[1,]) == 1){ |
929 | ! |
as.matrix(apply(spans, 1, truncate_one_span, j = j)) |
930 |
} |
|
931 |
else |
|
932 | 68x |
t(apply(spans, 1, truncate_one_span, j = j)) |
933 |
} |
|
934 | ||
935 | ||
936 |
mpf_subset_rows <- function(mf, i) { |
|
937 | 41x |
nlh <- mf_nlheader(mf) |
938 | 41x |
lgrps <- mf_lgrouping(mf) |
939 | 41x |
row_lgrps <- tail(lgrps, -1*nlh) |
940 | 41x |
nrs <- length(unique(row_lgrps)) |
941 | 41x |
ncolrows <- length(unique(lgrps[seq_len(nlh)])) |
942 | ||
943 | 41x |
ncs <- ncol(mf) |
944 | 41x |
mf <- .mf_subset_core_mats(mf, i, row = TRUE) |
945 | 41x |
map <- data.frame(old_idx = c(seq_len(ncolrows), i + ncolrows), |
946 | 41x |
new_idx = c(seq_len(ncolrows), ncolrows + order(i))) |
947 | ||
948 | 41x |
row_map <- data.frame(old_idx = i, new_idx = order(i)) |
949 | ||
950 | 41x |
refdf <- mf_fnote_df(mf) |
951 | ||
952 | 41x |
old_nas <- is.na(refdf$row) |
953 | 41x |
refdf$row <- map_to_new(refdf$row, row_map) |
954 | 41x |
refdf <- refdf[old_nas | !is.na(refdf$row),] |
955 | 41x |
refdf <- fix_fnote_df(refdf) |
956 | 41x |
mf_fnote_df(mf) <- refdf |
957 | ||
958 | 41x |
rinfo <- mf_rinfo(mf) |
959 | ||
960 | 41x |
rinfo <- rinfo[rinfo$abs_rownumber %in% i,] |
961 | ||
962 | 41x |
rinfo$abs_rownumber <- map_to_new(rinfo$abs_rownumber, row_map) |
963 | 41x |
mf_rinfo(mf) <- rinfo |
964 | ||
965 | 41x |
mf <- shove_refdf_into_rowinfo(mf) |
966 | 41x |
mf_rfnotes(mf) <- reconstruct_basic_fnote_list(mf) |
967 | 41x |
mf |
968 | ||
969 |
} |
|
970 | ||
971 | ||
972 | ||
973 |
## we only care about referential footnotes, cause |
|
974 |
## they are currently the only place we're tracking |
|
975 |
## column information that will need to be touched up |
|
976 |
## but lets be careful and do a bit more anyway |
|
977 |
mpf_subset_cols <- function(mf, j) { |
|
978 | ||
979 | 68x |
nc <- ncol(mf) |
980 | 68x |
if(is.logical(j) || all(j < 0)) |
981 | ! |
j <- seq_len(nc)[j] |
982 | 68x |
if(any(j < 0)) |
983 | ! |
stop("cannot mix negative and positive indices") |
984 | ||
985 | 68x |
if(length(unique(j)) != length(j)) |
986 | ! |
stop("duplicated columns are not allowed when subsetting a matrix print form objects") |
987 | ||
988 | ||
989 |
# j_mat <- c(if(mf_has_topleft(mf)) seq_len(nlabcol), j + nlabcol) |
|
990 | 68x |
map <- data.frame(old_idx = j, new_idx = order(j)) |
991 | ||
992 |
## this has to happen before the remap inher |
|
993 | 68x |
refdf <- mf_fnote_df(mf) |
994 | ||
995 | 68x |
mf <- .mf_subset_core_mats(mf, j, row = FALSE) |
996 | ||
997 | ||
998 |
## future proofing (pipe dreams) |
|
999 |
## uncomment if we ever manage to have col info information on MPFs |
|
1000 |
## if(!is.null(mf_cinfo(mf))) { |
|
1001 |
## cinfo <- mf_cinfo(mf) |
|
1002 |
## cinfo <- cinfo[j, , drop = FALSE] |
|
1003 |
## cinfo$abs_pos <- map_to_new(cinfo$abs_pos, map) |
|
1004 |
## mf_cinfo(mf) <- mf |
|
1005 |
## } |
|
1006 | ||
1007 | ||
1008 | ||
1009 | 68x |
keep <- is.na(refdf$col) | refdf$col %in% j |
1010 | 68x |
refdf <- refdf[keep, , drop = FALSE] |
1011 | ||
1012 | 68x |
refdf$col <- map_to_new(refdf$col, map) |
1013 | 68x |
mf_fnote_df(mf) <- refdf |
1014 | 68x |
mf <- shove_refdf_into_rowinfo(mf) |
1015 | 68x |
mf_rfnotes(mf) <- reconstruct_basic_fnote_list(mf) |
1016 | 68x |
mf_ncol(mf) <- length(j) |
1017 | 68x |
mf |
1018 |
} |
1 |
.need_pag <- function(page_type, pg_width, pg_height, cpp, lpp) { |
|
2 | ! |
!(is.null(page_type) && is.null(pg_width) && is.null(pg_height) && is.null(cpp) && is.null(lpp)) |
3 | ||
4 |
} |
|
5 | ||
6 |
#' Export a table-like object to plain (ASCII) text with page break |
|
7 |
#' |
|
8 |
#' This function converts \code{x} to a \code{MatrixPrintForm} object via |
|
9 |
#' \code{matrix_form}, paginates it via \code{paginate}, converts each |
|
10 |
#' page to ASCII text via \code{toString}, and emits the strings to \code{file}, |
|
11 |
#' separated by \code{page_break}. |
|
12 |
#' |
|
13 |
#' @inheritParams paginate_indices |
|
14 |
#' @inheritParams toString |
|
15 |
#' @inheritParams propose_column_widths |
|
16 |
#' @param x ANY. The table-like object to export. Must have an |
|
17 |
#' applicable \code{matrix_form} method. |
|
18 |
#' @param file character(1) or NULL. If non-NULL, the path to write a |
|
19 |
#' text file to containing the \code{x} rendered as ASCII text, |
|
20 |
#' @param page_break character(1). Page break symbol (defaults to |
|
21 |
#' outputting \code{"\\n\\s"}). |
|
22 |
#' @param paginate logical(1). Whether pagination should be performed, |
|
23 |
#' defaults to \code{TRUE} if page size is specified (including |
|
24 |
#' the default). |
|
25 |
#' @details if \code{x} has an \code{num_rep_cols} method, the value |
|
26 |
#' returned by it will be used for \code{rep_cols} by default, if |
|
27 |
#' not, 0 will be used. |
|
28 |
#' |
|
29 |
#' If \code{x} has an applicable \code{do_mand_paginate} method, it will be invoked |
|
30 |
#' during the pagination process. |
|
31 |
#' |
|
32 |
#' @return if \code{file} is NULL, the total paginated and then concatenated |
|
33 |
#' string value, otherwise the file that was written. |
|
34 |
#' @export |
|
35 |
#' @examples |
|
36 |
#' export_as_txt(basic_matrix_form(mtcars), pg_height = 5, pg_width = 4) |
|
37 | ||
38 |
export_as_txt <- function(x, |
|
39 |
file = NULL, |
|
40 |
page_type = NULL, |
|
41 |
landscape = FALSE, |
|
42 |
pg_width = page_dim(page_type)[if(landscape) 2 else 1], |
|
43 |
pg_height = page_dim(page_type)[if(landscape) 1 else 2], |
|
44 |
font_family = "Courier", |
|
45 |
font_size = 8, # grid parameters |
|
46 |
lineheight = 1L, |
|
47 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
48 |
paginate = TRUE, |
|
49 |
cpp = NA_integer_, |
|
50 |
lpp = NA_integer_, |
|
51 |
..., |
|
52 |
hsep = default_hsep(), |
|
53 |
indent_size = 2, |
|
54 |
tf_wrap = paginate, |
|
55 |
max_width = NULL, |
|
56 |
colwidths = NULL, |
|
57 |
min_siblings = 2, |
|
58 |
nosplitin = character(), |
|
59 |
rep_cols = num_rep_cols(x), |
|
60 |
verbose = FALSE, |
|
61 |
page_break = "\\s\\n") { |
|
62 | ||
63 | 3x |
if(paginate) { |
64 | 3x |
pages <- paginate_to_mpfs(x, |
65 | 3x |
page_type = page_type, |
66 | 3x |
font_family = font_family, |
67 | 3x |
font_size = font_size, |
68 | 3x |
lineheight = lineheight, |
69 | 3x |
landscape = landscape, |
70 | 3x |
pg_width = pg_width, |
71 | 3x |
pg_height = pg_height, |
72 | 3x |
margins = margins, |
73 | 3x |
lpp = lpp, |
74 | 3x |
cpp = cpp, |
75 | 3x |
min_siblings = min_siblings, |
76 | 3x |
nosplitin = nosplitin, |
77 | 3x |
colwidths = colwidths, |
78 | 3x |
tf_wrap = tf_wrap, |
79 | 3x |
max_width = max_width, |
80 | 3x |
indent_size = indent_size, |
81 | 3x |
verbose = verbose, |
82 | 3x |
rep_cols = rep_cols) |
83 |
} else { |
|
84 | ! |
mf <- matrix_form(x, TRUE, TRUE, indent_size = indent_size) |
85 | ! |
mf_col_widths(mf) <- colwidths %||% propose_column_widths(mf) |
86 | ! |
pages <- list(mf) |
87 |
} |
|
88 |
## we dont' set widths here because we already but that info on mpf |
|
89 |
## so its on each of the pages. |
|
90 | 3x |
strings <- vapply(pages, toString, "", widths = NULL, |
91 | 3x |
hsep = hsep, tf_wrap = tf_wrap, max_width = max_width) |
92 | 3x |
res <- paste(strings, collapse = page_break) |
93 | ||
94 | 3x |
if(is.null(file)) |
95 | 1x |
res |
96 |
else |
|
97 | 2x |
cat(res, file = file) |
98 |
} |
|
99 | ||
100 | ||
101 | ||
102 |
## ## TODO this needs to be in terms of a MPF, so ncol(tt) needs to change |
|
103 | ||
104 |
## ## if(!is.null(colwidths) && length(colwidths) != ncol(tt) + 1) |
|
105 |
## ## stop("non-null colwidths argument must have length ncol(tt) + 1 [", |
|
106 |
## ## ncol(tt) + 1, "], got length ", length(colwidths)) |
|
107 | ||
108 |
## mpf <- matrix_form(x, indent_rownames = TRUE) |
|
109 | ||
110 |
## ps_spec <- calc_lcpp(page_type = page_type, |
|
111 |
## landscape = landscape, |
|
112 |
## pg_width = pg_width, |
|
113 |
## pg_height = pg_height, |
|
114 |
## font_family = font_family, |
|
115 |
## cpp = cpp, |
|
116 |
## lpp = lpp) |
|
117 | ||
118 |
## ## This needs to return list(x) in cases where no pagination was necessary |
|
119 |
## idx_lst <- paginate(mpf, .page_size_spec = ps_spec, colwidths = colwidths, |
|
120 |
## tf_wrap = tf_wrap, ## XXX I think we don't need this |
|
121 |
## ...) |
|
122 | ||
123 |
## tbls <- lapply(idx_lst, function(ii) |
|
124 |
## ## XXX how do we partition the colwidths ??? |
|
125 |
## ## Also this is gross make it a function!!! |
|
126 |
## res <- paste(mapply(function(tb, cwidths, ...) { |
|
127 |
## ## 1 and +1 are because cwidths includes rowlabel 'column' |
|
128 |
## cinds <- c(1, .figure_out_colinds(tb, tt) + 1L) |
|
129 |
## toString(tb, widths = cwidths[cinds], ...) |
|
130 |
## }, |
|
131 |
## MoreArgs = list(hsep = hsep, |
|
132 |
## indent_size = indent_size, |
|
133 |
## tf_wrap = tf_wrap, |
|
134 |
## max_width = max_width, |
|
135 |
## cwidths = colwidths), |
|
136 |
## SIMPLIFY = FALSE, |
|
137 |
## tb = tbls), |
|
138 |
## collapse = page_break) |
|
139 | ||
140 |
## if(!is.null(file)) |
|
141 |
## cat(res, file = file) |
|
142 |
## else |
|
143 |
## res |
|
144 |
## } |
|
145 | ||
146 | ||
147 | ||
148 | ||
149 |
## In use, must be tested |
|
150 |
prep_header_line <- function(mf, i) { |
|
151 | 2x |
ret <- mf$strings[i, mf$display[i, , drop = TRUE], drop = TRUE] |
152 | 2x |
ret |
153 |
} |
|
154 | ||
155 |
## margin_lines_to_in <- function(margins, font_size, font_family) { |
|
156 |
## tmpfile <- tempfile(fileext = ".pdf") |
|
157 |
## gp_plot <- gpar(fontsize = font_size, fontfamily = font_family) |
|
158 |
## pdf(file = tmpfile, width = 20, height = 20) |
|
159 |
## on.exit({ |
|
160 |
## dev.off() |
|
161 |
## file.remove(tmpfile) |
|
162 |
## }) |
|
163 |
## grid.newpage() |
|
164 |
## pushViewport(plotViewport(margins = margins, gp = gp_plot)) |
|
165 |
## c( |
|
166 |
## bottom = convertHeight(unit(margins["bottom"], "lines"), "inches", valueOnly = TRUE), |
|
167 |
## left = convertWidth(unit(1, "strwidth", strrep("m", margins["left"])), "inches", valueOnly = TRUE), |
|
168 |
## top = convertHeight(unit(margins["top"], "lines"), "inches", valueOnly = TRUE), |
|
169 |
## right = convertWidth(unit(1, "strwidth", strrep("m", margins["right"])), "inches", valueOnly = TRUE) |
|
170 |
## ) |
|
171 |
## } |
|
172 | ||
173 | ||
174 | ||
175 | ||
176 |
mpf_to_dfbody <- function(mpf, colwidths) { |
|
177 | 2x |
mf <- matrix_form(mpf, indent_rownames = TRUE) |
178 | 2x |
nlr <- mf_nlheader(mf) |
179 | 2x |
if (is.null(colwidths)) { |
180 | ! |
colwidths <- propose_column_widths(mf) |
181 |
} |
|
182 | 2x |
mf$strings[1:nlr, 1] <- ifelse(nzchar(mf$strings[1:nlr, 1, drop = TRUE]), |
183 | 2x |
mf$strings[1:nlr, 1, drop = TRUE], |
184 | 2x |
strrep(" ", colwidths) |
185 |
) |
|
186 | ||
187 | ||
188 | 2x |
myfakedf <- as.data.frame(tail(mf$strings, -nlr)) |
189 | 2x |
myfakedf |
190 |
} |
|
191 | ||
192 | ||
193 |
#' Transform `MPF` to `RTF` |
|
194 |
#' |
|
195 |
#' Experimental export to `RTF` via the `r2rtf` package |
|
196 |
#' |
|
197 |
#' @inheritParams page_lcpp |
|
198 |
#' @inheritParams toString |
|
199 |
#' @inheritParams grid::plotViewport |
|
200 |
#' @param mpf `MatrixPrintForm`. `MatrixPrintForm` object. |
|
201 |
#' @param colwidths character(1). Column widths. |
|
202 |
#' @details This function provides a low-level coercion of a |
|
203 |
#' `MatrixPrintForm` object into text containing the corresponding |
|
204 |
#' table in `RTF`. Currently, no pagination is done at this level, |
|
205 |
#' and should be done prior to calling this function, though that |
|
206 |
#' may change in the future. |
|
207 |
#' |
|
208 |
#' @return An `RTF` object |
|
209 |
#' @export |
|
210 |
mpf_to_rtf <- function(mpf, |
|
211 |
colwidths = NULL, |
|
212 |
page_type = "letter", |
|
213 |
pg_width = page_dim(page_type)[if (landscape) 2 else 1], |
|
214 |
pg_height = page_dim(page_type)[if (landscape) 1 else 2], |
|
215 |
landscape = FALSE, |
|
216 |
margins = c(4, 4, 4, 4), |
|
217 |
font_size = 8, |
|
218 |
...) { |
|
219 | 2x |
if (!requireNamespace("r2rtf")) { |
220 | ! |
stop("RTF export requires the 'r2rtf' package, please install it.") |
221 |
} |
|
222 | 2x |
mpf <- matrix_form(mpf, indent_rownames = TRUE) |
223 | 2x |
nlr <- mf_nlheader(mpf) |
224 | 2x |
if (is.null(colwidths)) { |
225 | ! |
colwidths <- propose_column_widths(mpf) |
226 |
} |
|
227 | 2x |
mpf$strings[1:nlr, 1] <- ifelse(nzchar(mpf$strings[1:nlr, 1, drop = TRUE]), |
228 | 2x |
mpf$strings[1:nlr, 1, drop = TRUE], |
229 | 2x |
strrep(" ", colwidths) |
230 |
) |
|
231 | ||
232 | 2x |
myfakedf <- mpf_to_dfbody(mpf, colwidths) |
233 | ||
234 | 2x |
rtfpg <- r2rtf::rtf_page(myfakedf, |
235 | 2x |
width = pg_width, |
236 | 2x |
height = pg_height, |
237 | 2x |
orientation = if (landscape) "landscape" else "portrait", |
238 | 2x |
margin = c(0.1, 0.1, 0.1, 0.1, 0.1, 0.1), |
239 | 2x |
nrow = 10000L |
240 | 2x |
) ## dont allow r2rtf to restrict lines per page beyond actual real eastate |
241 | 2x |
rtfpg <- r2rtf::rtf_title(rtfpg, main_title(mpf), subtitles(mpf), text_font = 1) |
242 | 2x |
for (i in seq_len(nlr)) { |
243 | 2x |
hdrlndat <- prep_header_line(mpf, i) |
244 | 2x |
rtfpg <- r2rtf::rtf_colheader(rtfpg, |
245 | 2x |
paste(hdrlndat, collapse = " | "), |
246 | 2x |
col_rel_width = unlist(tapply(colwidths, |
247 | 2x |
cumsum(mpf$display[i, , drop = TRUE]), |
248 | 2x |
sum, |
249 | 2x |
simplify = FALSE |
250 |
)), |
|
251 | 2x |
border_top = c("", rep(if (i > 1) "single" else "", length(hdrlndat) - 1)), |
252 | 2x |
text_font = 9, ## this means Courier New for some insane reason |
253 | 2x |
text_font_size = font_size |
254 |
) |
|
255 |
} |
|
256 | ||
257 | 2x |
rtfpg <- r2rtf::rtf_body(rtfpg, |
258 | 2x |
col_rel_width = colwidths, |
259 | 2x |
text_justification = c("l", rep("c", ncol(myfakedf) - 1)), |
260 | 2x |
text_format = "", |
261 | 2x |
text_font = 9, |
262 | 2x |
text_font_size = font_size |
263 |
) |
|
264 | ||
265 | 2x |
for (i in seq_along(mpf$ref_footnotes)) { |
266 | 4x |
rtfpg <- r2rtf::rtf_footnote(rtfpg, |
267 | 4x |
mpf$ref_footnotes[i], |
268 | 4x |
border_top = if (i == 1) "single" else "", |
269 | 4x |
border_bottom = if (i == length(mpf$ref_footnotes)) "single" else "", |
270 | 4x |
text_font = 9 |
271 |
) |
|
272 |
} |
|
273 | ||
274 | 2x |
if (length(main_footer(mpf)) > 0) { |
275 | 2x |
rtfpg <- r2rtf::rtf_footnote(rtfpg, main_footer(mpf), text_font = 9) |
276 |
} |
|
277 | 2x |
if (length(prov_footer(mpf)) > 0) { |
278 | 2x |
rtfpg <- r2rtf::rtf_source(rtfpg, prov_footer(mpf), text_font = 9) |
279 |
} |
|
280 | ||
281 | 2x |
rtfpg |
282 |
} |
|
283 | ||
284 |
## Not currently in use, previous alternate ways to get to RTF |
|
285 | ||
286 |
## ## XXX Experimental. Not to be exported without approval |
|
287 |
## mpf_to_huxtable <- function(obj) { |
|
288 |
## if (!requireNamespace("huxtable")) { |
|
289 |
## stop("mpf_to_huxtable requires the huxtable package") |
|
290 |
## } |
|
291 |
## mf <- matrix_form(obj, indent_rownames = TRUE) |
|
292 |
## nlr <- mf_nlheader(mf) |
|
293 |
## myfakedf <- as.data.frame(tail(mf$strings, -nlr)) |
|
294 |
## ret <- huxtable::as_hux(myfakedf, add_colnames = FALSE) |
|
295 |
## mf$strings[!mf$display] <- "" |
|
296 |
## for (i in seq_len(nlr)) { |
|
297 |
## arglist <- c( |
|
298 |
## list(ht = ret, after = i - 1), |
|
299 |
## as.list(mf$strings[i, ]) |
|
300 |
## ) |
|
301 |
## ret <- do.call(huxtable::insert_row, arglist) |
|
302 | ||
303 |
## spanspl <- split( |
|
304 |
## seq_len(ncol(mf$strings)), |
|
305 |
## cumsum(mf$display[i, ]) |
|
306 |
## ) |
|
307 | ||
308 | ||
309 |
## for (j in seq_along(spanspl)) { |
|
310 |
## if (length(spanspl[[j]]) > 1) { |
|
311 |
## ret <- huxtable::merge_cells(ret, row = i, col = spanspl[[j]]) |
|
312 |
## } |
|
313 |
## } |
|
314 |
## } |
|
315 |
## ret <- huxtable::set_header_rows(ret, seq_len(nlr), TRUE) |
|
316 |
## huxtable::font(ret) <- "courier" |
|
317 |
## huxtable::font_size(ret) <- 6 |
|
318 |
## huxtable::align(ret)[ |
|
319 |
## seq_len(nrow(ret)), |
|
320 |
## seq_len(ncol(ret)) |
|
321 |
## ] <- mf$aligns |
|
322 |
## ret |
|
323 |
## } |
|
324 | ||
325 |
## ## XXX Experimental. Not to be exported without approval |
|
326 |
## mpf_to_rtf <- function(obj, ..., file) { |
|
327 |
## huxt <- mpf_to_huxtable(obj) |
|
328 |
## ## a bunch more stuff here |
|
329 |
## huxtable::quick_rtf(huxt, ..., file = file) |
|
330 |
## } |
|
331 | ||
332 | ||
333 | ||
334 | ||
335 |
## ## XXX Experimental. Not to be exported without approval |
|
336 |
## mpf_to_gt <- function(obj) { |
|
337 |
## requireNamespace("gt") |
|
338 |
## mf <- matrix_form(obj, indent_rownames = TRUE) |
|
339 |
## nlh <- mf_nlheader(mf) |
|
340 |
## body_df <- as.data.frame(mf$strings[-1 * seq_len(nlh), ]) |
|
341 |
## varnamerow <- mf_nrheader(mf) |
|
342 |
## ## detect if we have counts |
|
343 |
## if (any(nzchar(mf$formats[seq_len(nlh), ]))) { |
|
344 |
## varnamerow <- varnamerow - 1 |
|
345 |
## } |
|
346 | ||
347 |
## rlbl_lst <- as.list(mf$strings[nlh, , drop = TRUE]) |
|
348 |
## names(rlbl_lst) <- names(body_df) |
|
349 | ||
350 |
## ret <- gt::gt(body_df, rowname_col = "V1") |
|
351 |
## ret <- gt::cols_label(ret, .list = rlbl_lst) |
|
352 |
## if (nlh > 1) { |
|
353 |
## for (i in 1:(nlh - 1)) { |
|
354 |
## linedat <- mf$strings[i, , drop = TRUE] |
|
355 |
## splvec <- cumsum(mf$display[i, , drop = TRUE]) |
|
356 |
## spl <- split(seq_along(linedat), splvec) |
|
357 |
## for (j in seq_along(spl)) { |
|
358 |
## vns <- names(body_df)[spl[[j]]] |
|
359 |
## labval <- linedat[spl[[j]][1]] |
|
360 |
## ret <- gt::tab_spanner(ret, |
|
361 |
## label = labval, |
|
362 |
## columns = {{ vns }}, |
|
363 |
## level = nlh - i, |
|
364 |
## id = paste0(labval, j) |
|
365 |
## ) |
|
366 |
## } |
|
367 |
## } |
|
368 |
## } |
|
369 | ||
370 |
## ret <- gt::opt_css(ret, css = "th.gt_left { white-space:pre;}") |
|
371 | ||
372 |
## ret |
|
373 |
## } |
|
374 | ||
375 | ||
376 | ||
377 |
#' Export table to `RTF` |
|
378 |
#' |
|
379 |
#' Experimental export to the `RTF` format. |
|
380 |
#' |
|
381 |
#' @details `RTF` export occurs by via the following steps |
|
382 |
#' |
|
383 |
#' \itemize{ |
|
384 |
#' \item{the table is paginated to the page size (Vertically and horizontally)} |
|
385 |
#' \item{Each separate page is converted to a `MatrixPrintForm` and from there to `RTF`-encoded text} |
|
386 |
#' \item{Separate `RTFs` text chunks are combined and written out as a single `RTF` file} |
|
387 |
#' } |
|
388 |
#' |
|
389 |
#' Conversion of `MatrixPrintForm` objects to `RTF` is done via [formatters::mpf_to_rtf()]. |
|
390 |
#' @inheritParams export_as_txt |
|
391 |
#' @inheritParams toString |
|
392 |
#' @inheritParams grid::plotViewport |
|
393 |
#' @inheritParams paginate_to_mpfs |
|
394 |
#' @export |
|
395 | ||
396 |
export_as_rtf <- function(x, |
|
397 |
file = NULL, |
|
398 |
colwidths = propose_column_widths(matrix_form(x, TRUE)), |
|
399 |
page_type = "letter", |
|
400 |
pg_width = page_dim(page_type)[if(landscape) 2 else 1], |
|
401 |
pg_height = page_dim(page_type)[if(landscape) 1 else 2], |
|
402 |
landscape = FALSE, |
|
403 |
margins = c(bottom = .5, left = .75, top=.5, right = .75), |
|
404 |
font_size = 8, |
|
405 |
font_family = "Courier", |
|
406 |
...) { |
|
407 | 1x |
if(!requireNamespace("r2rtf")) |
408 | ! |
stop("RTF export requires the r2rtf package, please install it.") |
409 | 1x |
if(is.null(names(margins))) |
410 | ! |
names(margins) <- marg_order |
411 | ||
412 | 1x |
fullmf <- matrix_form(x, indent_rownames = TRUE) |
413 | 1x |
req_ncols <- ncol(fullmf) + as.numeric(mf_has_rlabels(fullmf)) |
414 | 1x |
if(!is.null(colwidths) && length(colwidths) != req_ncols) |
415 | ! |
stop("non-null colwidths argument must have length ncol(x) (+ 1 if row labels are present) [", |
416 | ! |
req_ncols, "], got length ", length(colwidths)) |
417 | ||
418 | 1x |
true_width <- pg_width - sum(margins[c("left", "right")]) |
419 | 1x |
true_height <- pg_height - sum(margins[c("top", "bottom")]) |
420 | ||
421 | 1x |
mpfs <- paginate_to_mpfs(fullmf, font_family = font_family, font_size = font_size, |
422 | 1x |
pg_width = true_width, |
423 | 1x |
pg_height = true_height, |
424 | 1x |
margins = c(bottom = 0, left = 0, top = 0, right = 0), |
425 | 1x |
lineheight = 1.25, |
426 | 1x |
colwidths = colwidths, |
427 |
...) |
|
428 | ||
429 | 1x |
rtftxts <- lapply(mpfs, function(mf) r2rtf::rtf_encode(mpf_to_rtf(mf, |
430 | 1x |
colwidths = mf_col_widths(mf), |
431 | 1x |
page_type = page_type, |
432 | 1x |
pg_width = pg_width, |
433 | 1x |
pg_height = pg_height, |
434 | 1x |
font_size = font_size, |
435 | 1x |
margins = c(top = 0, left = 0, bottom = 0, right = 0)))) |
436 | 1x |
restxt <- paste(rtftxts[[1]]$start, |
437 | 1x |
paste(sapply(rtftxts, function(x) x$body), collapse = "\n{\\pard\\fs2\\par}\\page{\\pard\\fs2\\par}\n"), |
438 | 1x |
rtftxts[[1]]$end) |
439 | 1x |
if(!is.null(file)) |
440 | 1x |
cat(restxt, file = file) |
441 |
else |
|
442 | ! |
restxt |
443 |
} |
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 | 1206x |
data.frame( |
138 | 1206x |
label = lab, |
139 | 1206x |
name = nm, |
140 | 1206x |
abs_rownumber = rnum, |
141 | 1206x |
path = I(list(pth)), |
142 | 1206x |
pos_in_siblings = sibpos, |
143 | 1206x |
n_siblings = nsibs, |
144 | 1206x |
self_extent = extent, |
145 | 1206x |
par_extent = repext, |
146 | 1206x |
reprint_inds = I(rep(list(unlist(repind)), length.out = length(nm))), |
147 | 1206x |
node_class = rclass, |
148 | 1206x |
indent = max(0L, indent), |
149 | 1206x |
nrowrefs = nrowrefs, |
150 | 1206x |
ncellrefs = ncellrefs, |
151 | 1206x |
nreflines = nreflines, |
152 |
# ref_info_df = I(list(ref_df)), |
|
153 | 1206x |
force_page = force_page, |
154 | 1206x |
page_title = page_title, |
155 | 1206x |
trailing_sep = trailing_sep, |
156 | 1206x |
stringsAsFactors = FALSE, |
157 | 1206x |
row.names = NULL, |
158 | 1206x |
check.names = FALSE, |
159 | 1206x |
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 | 450x |
if(is.null(pagdf$ref_info_df) && sum(pagdf$nreflines) == 0) |
167 | 202x |
return(ref_df_row()[0, ]) |
168 | 248x |
refdf <- do.call(rbind.data.frame, pagdf$ref_info_df) |
169 | 248x |
if(NROW(refdf) == 0) |
170 | 150x |
return(ref_df_row()[0, ]) |
171 | 98x |
unqsyms <- !duplicated(refdf$symbol) |
172 | 98x |
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 | 252x |
if(row) { |
180 | 105x |
spacetype <- "lines" |
181 | 105x |
spacetype_abr <- "lns" |
182 | 105x |
structtype_abr <- "rws" |
183 | 105x |
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 | 105x |
lines, |
185 | 105x |
spacetype, |
186 | 105x |
raw_rowlines, |
187 | 105x |
spacetype_abr, |
188 | 105x |
guess - start + 1, # because it includes both start and guess |
189 | 105x |
structtype_abr, |
190 | 105x |
rep_ext, |
191 | 105x |
spacetype_abr, |
192 | 105x |
n_reprint, |
193 | 105x |
structtype_abr, |
194 | 105x |
reflines, |
195 | 105x |
spacetype_abr, |
196 | 105x |
n_refs, |
197 | 105x |
sectlines, |
198 | 105x |
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 | 450x |
rw <- pagdf[guess, ] |
222 | ||
223 | ||
224 | 450x |
if (verbose) { |
225 | 421x |
message( |
226 | 421x |
"Checking pagination after ", |
227 | 421x |
paste(ifelse(row, "row", "column"), guess) |
228 |
) |
|
229 |
} |
|
230 | 450x |
raw_rowlines <- sum(pagdf[start:guess, "self_extent"] - pagdf[start:guess, "nreflines"]) |
231 | ||
232 | 450x |
refdf_ii <- calc_ref_nlines_df(pagdf[start:guess,]) |
233 | 450x |
reflines <- if(row) sum(refdf_ii$nlines, 0L) else 0L |
234 | 450x |
if (reflines > 0 && !have_col_fnotes) |
235 | 35x |
reflines <- reflines + div_height + 1L |
236 | ||
237 |
## reflines <- sum(pagdf[start:guess, "nreflines"]) |
|
238 | 450x |
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 | 450x |
sectlines <- if (start == guess) 0L else sum(!is.na(pagdf[start:(guess - 1), "trailing_sep"])) |
242 | 450x |
lines <- rowlines + sectlines # guess - start + 1 because inclusive of start |
243 | 450x |
rep_ext <- pagdf$par_extent[start] |
244 | 450x |
if(lines > rlpp) { |
245 | 268x |
if(verbose) { |
246 | 252x |
structtype <- ifelse(row, "rows", "columns") |
247 | 252x |
structtype_abr <- ifelse(row, "rows", "cols") |
248 | 252x |
spacetype <- ifelse(row, "lines", "chars") |
249 | 252x |
spacetype_abr <- ifelse(row, "lns", "chrs") |
250 | 252x |
msg <- build_fail_msg(row, lines, raw_rowlines, start, guess, rep_ext, length(pagdf$reprint_inds[[start]]),reflines, NROW(refdf_ii), sectlines) |
251 | 252x |
message(msg) |
252 |
} |
|
253 | 268x |
return(FALSE) |
254 |
} |
|
255 | 182x |
if (rw[["node_class"]] %in% c("LabelRow", "ContentRow")) { |
256 | 10x |
if (verbose) { |
257 | 10x |
message("\t....................... FAIL: last row is a label or content row") |
258 |
} |
|
259 | 10x |
return(FALSE) |
260 |
} |
|
261 | ||
262 | 172x |
sibpos <- rw[["pos_in_siblings"]] |
263 | 172x |
nsib <- rw[["n_siblings"]] |
264 |
# okpos <- min(min_sibs + 1, rw[["n_siblings"]]) |
|
265 | 172x |
if (sibpos != nsib) { |
266 | 108x |
retfalse <- FALSE |
267 | 108x |
if (sibpos < min_sibs + 1) { |
268 | 50x |
retfalse <- TRUE |
269 | 50x |
if (verbose) { |
270 | 50x |
message( |
271 | 50x |
"\t....................... FAIL: last row had only ", sibpos - 1, |
272 | 50x |
" preceding siblings, needed ", min_sibs |
273 |
) |
|
274 |
} |
|
275 | 58x |
} 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 | 108x |
if (retfalse) { |
285 | 54x |
return(FALSE) |
286 |
} |
|
287 |
} |
|
288 | 118x |
if (guess < nrow(pagdf) && length(nosplit > 0)) { |
289 |
## paths end at the leaf name which is *always* different |
|
290 | 32x |
curpth <- head(unlist(rw$path), -1) |
291 | 32x |
nxtpth <- head(unlist(pagdf$path[[guess + 1]]), -1) |
292 | ||
293 | 32x |
inplay <- nosplit[(nosplit %in% intersect(curpth, nxtpth))] |
294 | 32x |
if (length(inplay) > 0) { |
295 | 32x |
ok_split <- vapply(inplay, |
296 | 32x |
function(var) { |
297 | 32x |
!identical(curpth[match(var, curpth) + 1], |
298 | 32x |
nxtpth[match(var, nxtpth) + 1]) |
299 |
}, |
|
300 | 32x |
TRUE) |
301 | ||
302 | 32x |
curvals <- curpth[match(inplay, curpth) + 1] |
303 | 32x |
nxtvals <- nxtpth[match(inplay, nxtpth) + 1] |
304 | 32x |
if (!all(ok_split)) { |
305 | 32x |
if (verbose) { |
306 | 32x |
message( |
307 | 32x |
"\t....................... FAIL: nosplit variable [", |
308 | 32x |
inplay[min(which(!ok_split))], "] would be constant [", |
309 | 32x |
curvals, "] across this pagebreak.") |
310 |
} |
|
311 | 32x |
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 |
do_error = FALSE) { |
|
333 | 96x |
origuess <- guess |
334 | 96x |
while (guess >= start && !valid_pag(pagdf, guess, |
335 | 96x |
start = start, rlpp = rlpp, min_sibs = min_siblings, |
336 | 96x |
nosplit = nosplitin, verbose, row = row, have_col_fnotes = have_col_fnotes, |
337 | 96x |
div_height = div_height |
338 |
)) { |
|
339 | 364x |
guess <- guess - 1 |
340 |
} |
|
341 | 96x |
if (guess < start) { |
342 | 10x |
if (isFALSE(do_error)) { |
343 | 5x |
find_pag(pagdf = pagdf, |
344 | 5x |
start = start, |
345 | 5x |
guess = origuess, |
346 | 5x |
rlpp = rlpp, |
347 | 5x |
min_siblings = min_siblings, |
348 | 5x |
nosplitin = nosplitin, |
349 | 5x |
verbose = TRUE, |
350 | 5x |
row = row, |
351 | 5x |
have_col_fnotes = have_col_fnotes, |
352 | 5x |
div_height = div_height, |
353 | 5x |
do_error = TRUE) |
354 |
} |
|
355 | 5x |
stop("Unable to find any valid pagination split\ between ", ifelse(row, "rows ", "columns "), start, " and ", origuess, |
356 | 5x |
". \n", |
357 | 5x |
"Inserted ", ifelse(row, "cpp (column-space, content per page) ", |
358 | 5x |
"lpp (row-space, lines per page) "), |
359 | 5x |
": ", pagdf$par_extent[start] + rlpp, "\n", |
360 | 5x |
"Need-to-repeat-in-each-page space (key values): ", pagdf$par_extent[start], "\n", |
361 | 5x |
"Remaining space: ", rlpp, "\n", |
362 | 5x |
"Current space needed (with padding): ", pagdf$self_extent[start]) |
363 |
} |
|
364 | 86x |
guess |
365 |
} |
|
366 | ||
367 | ||
368 |
#' Find Pagination Indices From Pagination Info Dataframe |
|
369 |
#' |
|
370 |
#' Pagination methods should typically call the `make_row_df` method |
|
371 |
#' for their object and then call this function on the resulting |
|
372 |
#' pagination info data.frame. |
|
373 |
#' |
|
374 |
#' @details `pab_indices_inner` implements the Core Pagination Algorithm |
|
375 |
#' for a single direction (vertical if `row = TRUE`, the default, horizontal otherwise) |
|
376 |
#' based on the pagination dataframe and (already adjusted for non-body rows/columns) |
|
377 |
#' lines (or characters) per page. |
|
378 |
#' |
|
379 |
#' @inheritSection pagination_algo Pagination Algorithm |
|
380 |
#' @param pagdf data.frame. A pagination info data.frame as created by |
|
381 |
#' either `make_rows_df` or `make_cols_df`. |
|
382 |
#' @param rlpp numeric. Maximum number of \emph{row} lines per page (not including header materials), including |
|
383 |
#' (re)printed header and context rows |
|
384 |
#' @param min_siblings numeric. Minimum sibling rows which must appear on either side of pagination row for a |
|
385 |
#' mid-subtable split to be valid. Defaults to 2. |
|
386 |
#' @param nosplitin character. List of names of sub-tables where page-breaks are not allowed, regardless of other |
|
387 |
#' considerations. Defaults to none. |
|
388 |
#' @param verbose logical(1). Should additional informative messages about the search for |
|
389 |
#' pagination breaks be shown. Defaults to \code{FALSE}. |
|
390 |
#' @param row logical(1). Is pagination happening in row |
|
391 |
#' space (`TRUE`, the default) or column space (`FALSE`) |
|
392 |
#' @param have_col_fnotes logical(1). Does the table-like object being rendered have |
|
393 |
#' column-associated referential footnotes. |
|
394 |
#' @param div_height numeric(1). The height of the divider line when the |
|
395 |
#' associated object is rendered. Defaults to `1`. |
|
396 |
#' @return A list containing the vector of row numbers, broken up by page |
|
397 |
#' |
|
398 |
#' @examples |
|
399 |
#' mypgdf <- basic_pagdf(row.names(mtcars)) |
|
400 |
#' |
|
401 |
#' paginds <- pag_indices_inner(mypgdf, rlpp = 15, min_siblings = 0) |
|
402 |
#' lapply(paginds, function(x) mtcars[x, ]) |
|
403 |
#' |
|
404 |
#' @export |
|
405 |
pag_indices_inner <- function(pagdf, rlpp, |
|
406 |
min_siblings, |
|
407 |
nosplitin = character(), |
|
408 |
verbose = FALSE, |
|
409 |
row = TRUE, |
|
410 |
have_col_fnotes = FALSE, |
|
411 |
div_height = 1L) { |
|
412 | 37x |
start <- 1 |
413 | 37x |
nr <- nrow(pagdf) |
414 | 37x |
ret <- list() |
415 | 37x |
while (start <= nr) { |
416 | 92x |
adjrlpp <- rlpp - pagdf$par_extent[start] |
417 | 92x |
if (adjrlpp <= 0) { |
418 | 1x |
if (row) { |
419 | 1x |
stop("Lines of repeated context (plus header materials) larger than specified lines per page") |
420 |
} else { |
|
421 | ! |
stop("Width of row labels equal to or larger than specified characters per page.") |
422 |
} |
|
423 |
} |
|
424 | 91x |
guess <- min(nr, start + adjrlpp - 1) |
425 | 91x |
end <- find_pag(pagdf, start, guess, |
426 | 91x |
rlpp = adjrlpp, |
427 | 91x |
min_siblings = min_siblings, |
428 | 91x |
nosplitin = nosplitin, |
429 | 91x |
verbose = verbose, |
430 | 91x |
row = row, |
431 | 91x |
have_col_fnotes = have_col_fnotes, |
432 | 91x |
div_height = div_height |
433 |
) |
|
434 | 86x |
ret <- c(ret, list(c( |
435 | 86x |
pagdf$reprint_inds[[start]], |
436 | 86x |
start:end |
437 |
))) |
|
438 | 86x |
start <- end + 1 |
439 |
} |
|
440 | 31x |
ret |
441 |
} |
|
442 | ||
443 |
#' Find Column Indices for Vertical Pagination |
|
444 |
#' @param obj ANY. object to be paginated. Must have a |
|
445 |
#' \code{\link{matrix_form}} method. |
|
446 |
#' @param cpp numeric(1). Number of characters per page (width) |
|
447 |
#' @param colwidths numeric vector. Column widths (in characters) for |
|
448 |
#' use with vertical pagination. |
|
449 |
#' @param rep_cols numeric(1). Number of \emph{columns} (not including |
|
450 |
#' row labels) to be repeated on every page. Defaults to 0 |
|
451 |
#' @inheritParams pag_indices_inner |
|
452 |
#' |
|
453 |
#' @return A list partitioning the vector of column indices |
|
454 |
#' into subsets for 1 or more horizontally paginated pages. |
|
455 |
#' |
|
456 |
#' @examples |
|
457 |
#' mf <- basic_matrix_form(df = mtcars) |
|
458 |
#' colpaginds <- vert_pag_indices(mf) |
|
459 |
#' lapply(colpaginds, function(j) mtcars[, j, drop = FALSE]) |
|
460 |
#' @export |
|
461 |
vert_pag_indices <- function(obj, cpp = 40, colwidths = NULL, verbose = FALSE, rep_cols = 0L) { |
|
462 | 16x |
mf <- matrix_form(obj, TRUE) |
463 | 16x |
clwds <- colwidths %||% propose_column_widths(mf) |
464 | 16x |
if(is.null(mf_cinfo(mf))) ## like always, ugh. |
465 | 2x |
mf <- mpf_infer_cinfo(mf, colwidths = clwds, rep_cols = rep_cols) |
466 | ||
467 | 16x |
has_rlabs <- mf_has_rlabels(mf) |
468 | 16x |
rlabs_flag <- as.integer(has_rlabs) |
469 | 16x |
rlab_extent <- if (has_rlabs) clwds[1] else 0L |
470 | ||
471 |
# rep_extent <- pdf$par_extent[nrow(pdf)] |
|
472 | 16x |
rcpp <- cpp - table_inset(mf) - rlab_extent # rep_extent - table_inset(mf) - rlab_extent |
473 | 16x |
if (verbose) { |
474 | 12x |
message( |
475 | 12x |
"Adjusted characters per page: ", rcpp, |
476 | 12x |
" [original: ", cpp, |
477 | 12x |
", table inset: ", table_inset(mf), if (has_rlabs) paste0(", row labels: ", clwds[1]), |
478 |
"]" |
|
479 |
) |
|
480 |
} |
|
481 | 16x |
res <- pag_indices_inner(mf_cinfo(mf), |
482 | 16x |
rlpp = rcpp, # cpp - sum(clwds[seq_len(rep_cols)]), |
483 | 16x |
verbose = verbose, |
484 | 16x |
min_siblings = 1, |
485 | 16x |
row = FALSE |
486 |
) |
|
487 | 16x |
res |
488 |
} |
|
489 | ||
490 |
mpf_infer_cinfo <- function(mf, colwidths = NULL, rep_cols = num_rep_cols(mf)) { |
|
491 | ||
492 | 46x |
if (!is(rep_cols, "numeric") || is.na(rep_cols) || rep_cols < 0) { |
493 | ! |
stop("got invalid number of columns to be repeated: ", rep_cols) |
494 |
} |
|
495 | 46x |
clwds <- (colwidths %||% mf_col_widths(mf)) %||% propose_column_widths(mf) |
496 | 46x |
has_rlabs <- mf_has_rlabels(mf) |
497 | 46x |
rlabs_flag <- as.integer(has_rlabs) |
498 | 46x |
rlab_extent <- if (has_rlabs) clwds[1] else 0L |
499 | 46x |
sqstart <- rlabs_flag + 1L # rep_cols + 1L |
500 | ||
501 | 46x |
pdfrows <- lapply( |
502 | 46x |
(sqstart):ncol(mf$strings), |
503 | 46x |
function(i) { |
504 | 494x |
rownum <- i - rlabs_flag |
505 | 494x |
rep_inds <- seq_len(rep_cols)[seq_len(rep_cols) < rownum] |
506 | 494x |
rep_extent_i <- sum(0L, clwds[rlabs_flag + rep_inds]) + mf$col_gap * length(rep_inds) |
507 | 494x |
pagdfrow( |
508 | 494x |
row = NA, |
509 | 494x |
nm = rownum, |
510 | 494x |
lab = rownum, |
511 | 494x |
rnum = rownum, |
512 | 494x |
pth = NA, |
513 | 494x |
extent = clwds[i] + mf$col_gap, |
514 | 494x |
repext = rep_extent_i, # sum(clwds[rep_cols]) + mf$col_gap * max(0, (length(rep_cols) - 1)), |
515 | 494x |
repind = rep_inds, # rep_cols, |
516 | 494x |
rclass = "stuff", |
517 | 494x |
sibpos = 1 - 1, |
518 | 494x |
nsibs = 1 - 1 |
519 |
) |
|
520 |
} |
|
521 |
) |
|
522 | 46x |
pdf <- do.call(rbind, pdfrows) |
523 | ||
524 | 46x |
refdf <- mf_fnote_df(mf) |
525 | 46x |
pdf <- splice_fnote_info_in(pdf, refdf, row = FALSE) |
526 | 46x |
mf_cinfo(mf) <- pdf |
527 | 46x |
mf |
528 |
} |
|
529 | ||
530 | ||
531 |
#' Basic/spoof pagination info dataframe |
|
532 |
#' |
|
533 |
#' Returns a minimal pagination info data.frame (with no sibling/footnote/etc info). |
|
534 |
#' @inheritParams basic_matrix_form |
|
535 |
#' @param rnames character. Vector of row names |
|
536 |
#' @param labs character. Vector of row labels (defaults to names) |
|
537 |
#' @param rnums integer. Vector of row numbers. Defaults to `seq_along(rnames)`. |
|
538 |
#' @param extents integer. Number of lines each row will take to print, defaults to 1 for all rows |
|
539 |
#' @param rclass character. Class(es) for the rows. Defaults to "NA" |
|
540 |
#' |
|
541 |
#' @return A data.frame suitable for use in both the `matrix_print_form` constructor and the pagination machinery |
|
542 |
#' |
|
543 |
#' @examples |
|
544 |
#' |
|
545 |
#' basic_pagdf(c("hi", "there")) |
|
546 |
#' @export |
|
547 |
basic_pagdf <- function(rnames, labs = rnames, rnums = seq_along(rnames), |
|
548 |
extents = 1L, |
|
549 |
rclass = "NA", |
|
550 |
parent_path = "root") { |
|
551 | 27x |
rws <- mapply(pagdfrow, |
552 | 27x |
nm = rnames, lab = labs, extent = extents, |
553 | 27x |
rclass = rclass, rnum = rnums, pth = lapply(rnames, function(x) c(parent_path, x)), |
554 | 27x |
SIMPLIFY = FALSE, nsibs = 1, sibpos = 1 |
555 |
) |
|
556 | 27x |
res <- do.call(rbind.data.frame, rws) |
557 | 27x |
res$n_siblings <- nrow(res) |
558 | 27x |
res$pos_in_siblings <- seq_along(res$n_siblings) |
559 | 27x |
res |
560 |
} |
|
561 | ||
562 | ||
563 | ||
564 | ||
565 |
## write paginate() which operates **solely** on a MatrixPrintForm obj |
|
566 | ||
567 | ||
568 |
page_size_spec <- function(lpp, cpp, max_width) { |
|
569 | 21x |
structure(list(lpp = lpp, |
570 | 21x |
cpp = cpp, |
571 | 21x |
max_width = max_width), |
572 | 21x |
class = "page_size_spec") |
573 |
} |
|
574 | ||
575 | ||
576 | 42x |
non_null_na <- function(x) !is.null(x) && is.na(x) |
577 | ||
578 | ||
579 |
calc_lcpp <- function(page_type = NULL, |
|
580 |
landscape = FALSE, |
|
581 |
pg_width = page_dim(page_type)[if(landscape) 2 else 1], |
|
582 |
pg_height = page_dim(page_type)[if(landscape) 1 else 2], |
|
583 |
font_family = "Courier", |
|
584 |
font_size = 8, # grid parameters |
|
585 |
cpp = NA_integer_, |
|
586 |
lpp = NA_integer_, |
|
587 |
tf_wrap = TRUE, |
|
588 |
max_width = NULL, |
|
589 |
lineheight = 1, |
|
590 |
margins = c(bottom = .5, left = .75, top = .5, right = .75), |
|
591 |
colwidths, |
|
592 |
col_gap, |
|
593 |
inset |
|
594 |
) { |
|
595 | ||
596 | 21x |
pg_lcpp <- page_lcpp(page_type = page_type, |
597 | 21x |
landscape = landscape, |
598 | 21x |
font_family = font_family, |
599 | 21x |
font_size = font_size, |
600 | 21x |
lineheight = lineheight, |
601 | 21x |
margins = margins, |
602 | 21x |
pg_width = pg_width, |
603 | 21x |
pg_height = pg_height) |
604 | ||
605 | 21x |
if (non_null_na(lpp)) { |
606 | 13x |
lpp <- pg_lcpp$lpp |
607 |
} |
|
608 | 21x |
if(non_null_na(cpp)) { |
609 | 14x |
cpp <- pg_lcpp$cpp |
610 |
} |
|
611 | 21x |
stopifnot(!is.na(cpp)) |
612 | 21x |
if(!tf_wrap && !is.null(max_width)) { |
613 | ! |
warning("tf_wrap is FALSE - ignoring non-null max_width value.") |
614 | ! |
max_width <- NULL |
615 | 21x |
} else if(tf_wrap && is.null(max_width)) |
616 | 5x |
max_width <- cpp |
617 | ||
618 | 21x |
if(is.character(max_width) && identical(max_width, "auto")) { |
619 | ! |
max_width <- inset + sum(colwidths) + (length(colwidths) - 1) * col_gap |
620 |
} |
|
621 | 21x |
page_size_spec(lpp = lpp, cpp = cpp, max_width = max_width) |
622 |
} |
|
623 | ||
624 | ||
625 |
calc_rlpp <- function(pg_size_spec, mf, colwidths, tf_wrap, verbose) { |
|
626 | 19x |
lpp <- pg_size_spec$lpp |
627 | 19x |
max_width = pg_size_spec$max_width |
628 | ||
629 | 19x |
dh <- divider_height(mf) |
630 | 19x |
if (any(nzchar(all_titles(mf)))) { |
631 |
## +1 is for blank line between subtitles and divider |
|
632 |
## dh is for divider line **between subtitles and column labels** |
|
633 |
## other divider line is accounted for in cinfo_lines |
|
634 | 11x |
if(!tf_wrap) |
635 | 9x |
tlines <- length(all_titles(mf)) |
636 |
else |
|
637 | 2x |
tlines <- sum(nlines(all_titles(mf), colwidths = colwidths, |
638 | 2x |
max_width = max_width)) |
639 | 11x |
tlines <- tlines + dh + 1L |
640 |
} else { |
|
641 | 8x |
tlines <- 0 |
642 |
} |
|
643 | ||
644 |
## dh for divider line between column labels and table body |
|
645 | 19x |
cinfo_lines <- mf_nlheader(mf) + dh |
646 | ||
647 | 19x |
if(verbose) |
648 | 15x |
message("Determining lines required for header content: ", |
649 | 15x |
tlines, " title and ", cinfo_lines, " table header lines") |
650 | ||
651 | 19x |
refdf <- mf_fnote_df(mf) |
652 | 19x |
cfn_df <- refdf[is.na(refdf$row) & !is.na(refdf$col),] |
653 | ||
654 | 19x |
flines <- 0L |
655 | 19x |
mnfoot <- main_footer(mf) |
656 | 19x |
havemn <- length(mnfoot) && any(nzchar(mnfoot)) |
657 | 19x |
if(havemn) |
658 | 12x |
flines <- nlines(mnfoot, colwidths = colwidths, |
659 | 12x |
max_width = max_width - table_inset(mf)) |
660 | 19x |
prfoot <- prov_footer(mf) |
661 | 19x |
if(length(prfoot) && any(nzchar(prfoot))) { |
662 | 11x |
flines <- flines + nlines(prov_footer(mf), colwidths = colwidths, max_width = max_width) |
663 | 11x |
if(havemn) |
664 | 11x |
flines <- flines + 1L ## space between main and prov footer. |
665 |
} |
|
666 |
## this time its for the divider between the footers and whatever is above them |
|
667 |
## (either table body or referential footnotes) |
|
668 | 19x |
if(flines > 0) |
669 | 12x |
flines <- flines + dh + 1L |
670 |
## this time its for the divider between the referential footnotes and |
|
671 |
## the table body IFF we have any, otherwise that divider+blanks pace doesn't get drawn |
|
672 | 19x |
if(NROW(cfn_df) > 0) { |
673 | ! |
cinfo_lines <- cinfo_lines + sum(cfn_df$nlines) |
674 | ! |
flines <- flines + dh + 1L |
675 |
} |
|
676 | ||
677 | 19x |
if(verbose) |
678 | 15x |
message("Determining lines required for footer content", |
679 | 15x |
if(NROW(cfn_df) > 0) " [column fnotes present]", |
680 | 15x |
": ", flines, " lines") |
681 | ||
682 | 19x |
ret <- lpp - flines - tlines - cinfo_lines |
683 | ||
684 | 19x |
if(verbose) |
685 | 15x |
message("Lines per page available for tables rows: ", ret, " (original: ", lpp, ")") |
686 | 19x |
ret |
687 |
} |
|
688 | ||
689 | ||
690 |
calc_rcpp <- function(pg_size_spec, mf, colwidths) { |
|
691 | ||
692 | ! |
cpp <- pg_size_spec$cpp |
693 | ||
694 | ! |
cpp - table_inset(mf) - colwidths[1] - mf_colgap(mf) |
695 |
} |
|
696 | ||
697 | ||
698 |
splice_idx_lists <- function(lsts) { |
|
699 | ! |
list(pag_row_indices = do.call(c, lapply(lsts, function(xi) xi$pag_row_indices)), |
700 | ! |
pag_col_indices = do.call(c, lapply(lsts, function(yi) yi$pag_col_indices))) |
701 | ||
702 |
} |
|
703 | ||
704 | ||
705 | ||
706 |
#' @title Paginate a table-like object for rendering |
|
707 |
#' |
|
708 |
#' @description |
|
709 |
#' These functions perform or diagnose bi-directional pagination on |
|
710 |
#' an object. |
|
711 |
#' |
|
712 |
#' `paginate_to_mpfs` renders `obj` into the `MatrixPrintForm` (`MPF`) |
|
713 |
#' intermediate representation, and then paginates that `MPF` into |
|
714 |
#' component `MPF`s each corresponding to an individual page and |
|
715 |
#' returns those in a list. |
|
716 |
#' |
|
717 |
#' `paginate_indices` renders `obj` into an `MPF`, then uses |
|
718 |
#' that representation to calculate the rows and columns of |
|
719 |
#' `obj` corresponding to each page of the pagination of `obj`, |
|
720 |
#' but simply returns these indices rather than paginating |
|
721 |
#' \code{obj} itself (see details for an important caveat). |
|
722 |
#' |
|
723 |
#' `diagnose_pagination` attempts pagination via `paginate_to_mpfs` |
|
724 |
#' and then returns diagnostic information which explains why page |
|
725 |
#' breaks were positioned where they were, or alternatively why |
|
726 |
#' no valid paginations could be found. |
|
727 |
#' |
|
728 |
#' @details |
|
729 |
#' |
|
730 |
#' All three of these functions generally support all classes which have |
|
731 |
#' a corresponding `matrix_form` method which returns a valid `MatrixPrintForm` |
|
732 |
#' object (including `MatrixPrintForm` objects themselves). |
|
733 |
#' |
|
734 |
#' `paginate_indices` is directly called by `paginate_to_mpfs` (and thus |
|
735 |
#' `diagnose_pagination`). For most classes, and most tables represented |
|
736 |
#' by supported classes, calling `paginate_to_mpfs` is equivalent to a |
|
737 |
#' manual `paginate_indices -> subset obj into pages -> matrix_form` |
|
738 |
#' workflow. |
|
739 |
#' |
|
740 |
#' The exception to this equivalence is objects which support 'forced pagination', |
|
741 |
#' or pagination logic which built into the object itself rather than being a |
|
742 |
#' function of space on a page. Forced pagination generally involves the creation |
|
743 |
#' of, e.g., page-specific titles which apply to these forced paginations. |
|
744 |
#' `paginate_to_mpfs` and `diagnose_pagination` support forced pagination by |
|
745 |
#' automatically calling the `do_forced_pagination` generic on the object |
|
746 |
#' and then paginating each object returned by that generic separately. The |
|
747 |
#' assumption here, then, is that page-specific titles and such are |
|
748 |
#' handled by the class' `do_forced_pagination` method. |
|
749 |
#' |
|
750 |
#' `paginate_indices`, on the other hand, \emph{does not support forced pagination}, |
|
751 |
#' because it returns only a set of indices for row and column subsetting for each page, |
|
752 |
#' and thus cannot retain any changes, e.g., to titles, done within `do_forced_paginate`. |
|
753 |
#' `paginate_indices` does call `do_forced_paginate`, but instead of continuing, it |
|
754 |
#' throws an error in the case that the result is more than a single "page". |
|
755 |
#' |
|
756 |
#' @inheritParams vert_pag_indices |
|
757 |
#' @inheritParams pag_indices_inner |
|
758 |
#' @inheritParams page_lcpp |
|
759 |
#' @inheritParams toString |
|
760 |
#' @inheritParams propose_column_widths |
|
761 |
#' @param lpp numeric(1) or NULL. Lines per page. if NA (the default, |
|
762 |
#' this is calculated automatically based on the specified page |
|
763 |
#' size). `NULL` indicates no vertical pagination should occur. |
|
764 |
#' @param cpp numeric(1) or NULL. Width in characters per page. if NA (the default, |
|
765 |
#' this is calculated automatically based on the specified page |
|
766 |
#' size). `NULL` indicates no horizontal pagination should occur. |
|
767 | ||
768 |
#' @param pg_size_spec page_size_spec. A pre-calculated page |
|
769 |
#' size specification. Typically this is not set in end user code. |
|
770 |
#' @param col_gap numeric(1). Currently unused. |
|
771 |
#' @return for `paginate_indices` a list with two elements of the same |
|
772 |
#' length: `pag_row_indices`, and `pag_col_indices`. For |
|
773 |
#' `paginate_to_mpfs`, a list of `MatrixPrintForm` objects |
|
774 |
#' representing each individual page after pagination (including |
|
775 |
#' forced pagination if necessary). |
|
776 |
#' @export |
|
777 |
#' @aliases paginate pagination |
|
778 |
#' @examples |
|
779 |
#' mpf <- basic_matrix_form(mtcars) |
|
780 |
#' |
|
781 |
#' paginate_indices(mpf, pg_width = 5, pg_height = 3) |
|
782 |
#' |
|
783 |
#' paginate_to_mpfs(mpf, pg_width = 5, pg_height = 3) |
|
784 |
paginate_indices <- function(obj, |
|
785 |
page_type = "letter", |
|
786 |
font_family = "Courier", |
|
787 |
font_size = 8, |
|
788 |
lineheight = 1, |
|
789 |
landscape = FALSE, |
|
790 |
pg_width = NULL, |
|
791 |
pg_height = NULL, |
|
792 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
793 |
lpp = NA_integer_, |
|
794 |
cpp = NA_integer_, |
|
795 |
min_siblings = 2, |
|
796 |
nosplitin = character(), |
|
797 |
colwidths = NULL, |
|
798 |
tf_wrap = FALSE, |
|
799 |
max_width = NULL, |
|
800 |
indent_size = 2, |
|
801 |
pg_size_spec = NULL, |
|
802 |
rep_cols = num_rep_cols(obj), |
|
803 |
col_gap = 3, |
|
804 |
verbose = FALSE) { |
|
805 | ||
806 | ||
807 |
## this MUST alsways return a list, inluding list(obj) when |
|
808 |
## no forced pagination is needed! otherwise stuff breaks for things |
|
809 |
## based on s3 classes that are lists underneath!!! |
|
810 | 21x |
fpags <- do_forced_paginate(obj) |
811 | ||
812 |
## if we have more than one forced "page", |
|
813 |
## paginate each of them individually and return the result. |
|
814 |
## forced pagination is ***currently*** only vertical, so |
|
815 |
## we don't have to worry about divying up colwidths here, |
|
816 |
## but we will if we ever allow force_paginate to do horiz |
|
817 |
## pagination. |
|
818 | 21x |
if(length(fpags) > 1) { |
819 | 1x |
stop("forced pagination is required for this object (class: ", class(obj)[1], |
820 | 1x |
") this is not supported in paginate_indices. Use paginate_to_mpfs or call ", |
821 | 1x |
"do_forced_paginate on your object and paginate each returned section separately.") |
822 |
} |
|
823 | ||
824 | ||
825 |
## I'm not sure this is worth doing. |
|
826 |
## ## We can't support forced pagination here, but we can support calls to, |
|
827 |
## ## e.g., paginate_indices(do_forced_pag(tt)) |
|
828 |
## if(is.list(obj) && !is.object(obj)) { |
|
829 |
## res <- lapply(obj, paginate_indices, |
|
830 |
## page_type = page_type, |
|
831 |
## font_family = font_family, |
|
832 |
## font_size = font_size, |
|
833 |
## lineheight = lineheight, |
|
834 |
## landscape = landscape, |
|
835 |
## pg_width = pg_width, |
|
836 |
## pg_height = pg_height, |
|
837 |
## margins = margins, |
|
838 |
## lpp = lpp, |
|
839 |
## cpp = cpp, |
|
840 |
## tf_wrap = tf_wrap, |
|
841 |
## max_width = max_width, |
|
842 |
## colwidths = colwidths, |
|
843 |
## min_siblings = min_siblings, |
|
844 |
## nosplitin = nosplitin, |
|
845 |
## col_gap = col_gap, |
|
846 |
## ## not setting num_rep_cols here cause it wont' get it right |
|
847 |
## verbose = verbose) |
|
848 |
## return(splice_idx_lists(res)) |
|
849 |
## } |
|
850 |
## order is annoying here, since we won't actually need the mpf if |
|
851 |
## we run into forced pagination, but life is short and this should work fine. |
|
852 | 20x |
mpf <- matrix_form(obj, TRUE, TRUE, indent_size = indent_size) |
853 | 20x |
if(is.null(colwidths)) |
854 | 2x |
colwidths <- mf_col_widths(mpf) %||% propose_column_widths(mpf) |
855 |
else |
|
856 | 18x |
mf_col_widths(mpf) <- colwidths |
857 | 20x |
if(NROW(mf_cinfo(mpf)) == 0) |
858 | 20x |
mpf <- mpf_infer_cinfo(mpf, colwidths, rep_cols) |
859 | ||
860 | ||
861 | 20x |
if(is.null(pg_size_spec)) { |
862 | 2x |
pg_size_spec <- calc_lcpp(page_type = page_type, |
863 | 2x |
font_family = font_family, |
864 | 2x |
font_size = font_size, |
865 | 2x |
lineheight = lineheight, |
866 | 2x |
landscape = landscape, |
867 | 2x |
pg_width = pg_width, |
868 | 2x |
pg_height = pg_height, |
869 | 2x |
margins = margins, |
870 | 2x |
lpp = lpp, |
871 | 2x |
cpp = cpp, |
872 | 2x |
tf_wrap = tf_wrap, |
873 | 2x |
max_width = max_width, |
874 | 2x |
colwidths = colwidths, |
875 | 2x |
inset = table_inset(mpf), |
876 | 2x |
col_gap = col_gap) |
877 |
} |
|
878 | ||
879 |
## we can't support forced pagination in paginate_indices because |
|
880 |
## forced pagination is generally going to set page titles, which |
|
881 |
## we can't preserve when just returning lists of indices. |
|
882 |
## Instead we make a hard assumption here that any forced pagination |
|
883 |
## has already occured. |
|
884 | ||
885 | ||
886 | ||
887 | ||
888 | ||
889 |
## this wraps the cell contents AND shoves referential footnote |
|
890 |
## info into mf_rinfo(mpf) |
|
891 | 20x |
mpf <- do_cell_fnotes_wrap(mpf, colwidths, max_width, tf_wrap = tf_wrap) |
892 | ||
893 | 20x |
if(is.null(pg_size_spec$lpp)) |
894 | 1x |
pag_row_indices <- list(seq_len(mf_nrow(mpf))) |
895 |
else |
|
896 | 19x |
pag_row_indices <- pag_indices_inner(pagdf= mf_rinfo(mpf), |
897 | 19x |
rlpp = calc_rlpp(pg_size_spec, mpf, colwidths = colwidths, tf_wrap = tf_wrap, |
898 | 19x |
verbose = verbose), |
899 | 19x |
verbose = verbose, |
900 | 19x |
min_siblings = min_siblings, |
901 | 19x |
nosplitin = nosplitin) |
902 | ||
903 | 15x |
if(is.null(pg_size_spec$cpp)) |
904 | 1x |
pag_col_indices <- list(seq_len(mf_ncol(mpf))) |
905 |
else |
|
906 | 14x |
pag_col_indices <- vert_pag_indices(mpf, cpp = pg_size_spec$cpp, colwidths = colwidths, |
907 | 14x |
rep_cols = rep_cols, verbose = verbose) |
908 | ||
909 | 15x |
list(pag_row_indices = pag_row_indices, |
910 | 15x |
pag_col_indices = pag_col_indices) |
911 |
} |
|
912 | ||
913 | 18x |
setGeneric("has_page_title", function(obj) standardGeneric("has_page_title")) |
914 | ||
915 | 18x |
setMethod("has_page_title", "ANY", function(obj) length(page_titles(obj)) > 0) |
916 | ||
917 |
#' @rdname paginate_indices |
|
918 |
#' @export |
|
919 |
paginate_to_mpfs <- function(obj, |
|
920 |
page_type = "letter", |
|
921 |
font_family = "Courier", |
|
922 |
font_size = 8, |
|
923 |
lineheight = 1, |
|
924 |
landscape = FALSE, |
|
925 |
pg_width = NULL, |
|
926 |
pg_height = NULL, |
|
927 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
928 |
lpp = NA_integer_, |
|
929 |
cpp = NA_integer_, |
|
930 |
min_siblings = 2, |
|
931 |
nosplitin = character(), |
|
932 |
colwidths = NULL, |
|
933 |
tf_wrap = FALSE, |
|
934 |
max_width = NULL, |
|
935 |
indent_size = 2, |
|
936 |
pg_size_spec = NULL, |
|
937 |
rep_cols = num_rep_cols(obj), |
|
938 |
col_gap = 2, |
|
939 |
verbose = FALSE) { |
|
940 | 19x |
mpf <- matrix_form(obj, TRUE, TRUE, indent_size = indent_size) |
941 | 19x |
if(is.null(colwidths)) |
942 | 11x |
colwidths <- mf_col_widths(mpf) %||% propose_column_widths(mpf) |
943 |
else |
|
944 | 8x |
mf_col_widths(mpf) <- colwidths |
945 | 19x |
if(NROW(mf_cinfo(mpf)) == 0) |
946 | 19x |
mpf <- mpf_infer_cinfo(mpf, colwidths, rep_cols) |
947 | ||
948 | ||
949 | 19x |
if(is.null(pg_size_spec)) { |
950 | 17x |
pg_size_spec <- calc_lcpp(page_type = page_type, |
951 | 17x |
font_family = font_family, |
952 | 17x |
font_size = font_size, |
953 | 17x |
lineheight = lineheight, |
954 | 17x |
landscape = landscape, |
955 | 17x |
pg_width = pg_width, |
956 | 17x |
pg_height = pg_height, |
957 | 17x |
margins = margins, |
958 | 17x |
lpp = lpp, |
959 | 17x |
cpp = cpp, |
960 | 17x |
tf_wrap = tf_wrap, |
961 | 17x |
max_width = max_width, |
962 | 17x |
colwidths = colwidths, |
963 | 17x |
inset = table_inset(mpf), |
964 | 17x |
col_gap = col_gap) |
965 |
} |
|
966 |
## this MUST alsways return a list, inluding list(obj) when |
|
967 |
## no forced pagination is needed! otherwise stuff breaks for things |
|
968 |
## based on s3 classes that are lists underneath!!! |
|
969 | 19x |
fpags <- do_forced_paginate(obj) |
970 | ||
971 |
## if we have more than one forced "page", |
|
972 |
## paginate each of them individually and return the result. |
|
973 |
## forced pagination is ***currently*** only vertical, so |
|
974 |
## we don't have to worry about divying up colwidths here, |
|
975 |
## but we will if we ever allow force_paginate to do horiz |
|
976 |
## pagination. |
|
977 | 19x |
if(length(fpags) > 1) { |
978 | 1x |
deep_pag <- lapply(fpags, paginate_to_mpfs, |
979 | 1x |
pg_size_spec = pg_size_spec, |
980 | 1x |
colwidths = colwidths, |
981 | 1x |
min_siblings = min_siblings, |
982 | 1x |
nosplitin = nosplitin, |
983 | 1x |
verbose = verbose) |
984 | 1x |
return(unlist(deep_pag, recursive = FALSE)) |
985 | 18x |
} else if (has_page_title(fpags[[1]])) { |
986 | ! |
obj <- fpags[[1]] |
987 |
} |
|
988 | ||
989 | ||
990 |
## we run into forced pagination, but life is short and this should work fine. |
|
991 | 18x |
mpf <- matrix_form(obj, TRUE, TRUE, indent_size = indent_size) |
992 | 18x |
if(is.null(colwidths)) |
993 | ! |
colwidths <- mf_col_widths(mpf) %||% propose_column_widths(mpf) |
994 | 18x |
mf_col_widths(mpf) <- colwidths |
995 | ||
996 | 18x |
page_indices <- paginate_indices(obj = obj, |
997 |
## page_type = page_type, |
|
998 |
## font_family = font_family, |
|
999 |
## font_size = font_size, |
|
1000 |
## lineheight = lineheight, |
|
1001 |
## landscape = landscape, |
|
1002 |
## pg_width = pg_width, |
|
1003 |
## pg_height = pg_height, |
|
1004 |
## margins = margins, |
|
1005 | 18x |
pg_size_spec = pg_size_spec, |
1006 |
## lpp = lpp, |
|
1007 |
## cpp = cpp, |
|
1008 | 18x |
min_siblings = min_siblings, |
1009 | 18x |
nosplitin = nosplitin, |
1010 | 18x |
colwidths = colwidths, |
1011 | 18x |
tf_wrap = tf_wrap, |
1012 |
## max_width = max_width, |
|
1013 | 18x |
rep_cols = rep_cols, |
1014 | 18x |
verbose = verbose) |
1015 | ||
1016 |
# This needs to be fixed better |
|
1017 | 15x |
if (inherits(fpags[[1]], "listing_df") && length(fpags) < 2) { |
1018 | ! |
pagmats <- lapply( |
1019 | ! |
page_indices$pag_row_indices, |
1020 | ! |
function(ii) { |
1021 | ! |
mf_tmp <- matrix_form(obj[ii, ], TRUE, TRUE, indent_size = indent_size) |
1022 | ! |
mf_col_widths(mf_tmp) <- colwidths |
1023 | ! |
mf_tmp |
1024 |
} |
|
1025 |
) |
|
1026 |
} else { |
|
1027 | 15x |
pagmats <- lapply(page_indices$pag_row_indices, function(ii) { |
1028 | 34x |
mpf_subset_rows(mpf, ii) |
1029 |
}) |
|
1030 |
} |
|
1031 | ||
1032 |
## these chunks now carry around their (correctly subset) col widths... |
|
1033 | 15x |
res <- lapply(pagmats, function(matii) { |
1034 | 34x |
lapply(page_indices$pag_col_indices, function(jj) { |
1035 | 68x |
mpf_subset_cols(matii, jj) |
1036 |
}) |
|
1037 |
}) |
|
1038 | ||
1039 | 15x |
unlist(res, recursive = FALSE) |
1040 |
} |
|
1041 | ||
1042 | ||
1043 |
#' @importFrom utils capture.output |
|
1044 |
#' @details |
|
1045 |
#' |
|
1046 |
#' `diagnose_pagination` attempts pagination and then, regardless of success |
|
1047 |
#' or failure, returns diagnostic information about pagination |
|
1048 |
#' attempts (if any) after each row and column. |
|
1049 |
#' |
|
1050 |
#' The diagnostics data reflects the final time the pagination algorithm |
|
1051 |
#' evaluated a page break at the specified location, regardless of how |
|
1052 |
#' many times the position was assessed total. |
|
1053 |
#' |
|
1054 |
#' To get information about intermediate attempts, perform pagination |
|
1055 |
#' with `verbose = TRUE` and inspect the messages in order. |
|
1056 |
#' |
|
1057 |
#' @return For `diagnose_pagination` a list containing: |
|
1058 |
#' |
|
1059 |
#' \describe{ |
|
1060 |
#' \item{`lpp_diagnostics`}{diagnostic information regarding lines per page} |
|
1061 |
#' \item{`row_diagnostics`}{basic information about rows, whether pagination was attempted after each row, and the final result of such an attempt, if made} |
|
1062 |
#' \item{`cpp_diagnostics}{diagnostic information regarding columns per page} |
|
1063 |
#' \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} |
|
1064 |
#' } |
|
1065 |
#' |
|
1066 |
#' @note For `diagnose_pagination`, the column labels are not |
|
1067 |
#' displayed in the `col_diagnostics` element due to certain |
|
1068 |
#' internal implementation details; rather the diagnostics are |
|
1069 |
#' reported in terms of absolute (leaf) column position. This is a |
|
1070 |
#' known limitation, and may eventually be changed, but the |
|
1071 |
#' information remains useful as it is currently reported. |
|
1072 |
#' |
|
1073 |
#' @note `diagnose_pagination` is intended for interactive debugging |
|
1074 |
#' use and \emph{should not be programmed against}, as the exact |
|
1075 |
#' content and form of the verbose messages it captures and |
|
1076 |
#' returns is subject to change. |
|
1077 |
#' |
|
1078 |
#' @note because `diagnose_pagination` relies on `capture.output(type = "message")`, |
|
1079 |
#' it cannot be used within the `testthat` (and likely other) testing frameworks, |
|
1080 |
#' and likely cannot be used within `knitr`/`rmarkdown` contexts either, |
|
1081 |
#' as this clashes with those systems' capture of messages. |
|
1082 |
#' |
|
1083 |
#' @export |
|
1084 |
#' |
|
1085 |
#' @rdname paginate_indices |
|
1086 |
#' @examples |
|
1087 |
#' |
|
1088 |
#' diagnose_pagination(mpf, pg_width = 5, pg_height = 3) |
|
1089 |
#' clws <- propose_column_widths(mpf) |
|
1090 |
#' clws[1] <- floor(clws[1]/3) |
|
1091 |
#' dgnost <- diagnose_pagination(mpf, pg_width = 5, pg_height = 3, colwidths = clws) |
|
1092 |
#' try(diagnose_pagination(mpf, pg_width = 1)) #fails |
|
1093 |
#' |
|
1094 |
diagnose_pagination <- function(obj, |
|
1095 |
page_type = "letter", |
|
1096 |
font_family = "Courier", |
|
1097 |
font_size = 8, |
|
1098 |
lineheight = 1, |
|
1099 |
landscape = FALSE, |
|
1100 |
pg_width = NULL, |
|
1101 |
pg_height = NULL, |
|
1102 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
1103 |
lpp = NA_integer_, |
|
1104 |
cpp = NA_integer_, |
|
1105 |
min_siblings = 2, |
|
1106 |
nosplitin = character(), |
|
1107 |
colwidths = propose_column_widths(matrix_form(obj, TRUE)), |
|
1108 |
tf_wrap = FALSE, |
|
1109 |
max_width = NULL, |
|
1110 |
indent_size = 2, |
|
1111 |
pg_size_spec = NULL, |
|
1112 |
rep_cols = num_rep_cols(obj), |
|
1113 |
col_gap = 2, |
|
1114 |
verbose = FALSE, |
|
1115 |
...) { |
|
1116 | ||
1117 | ||
1118 | 6x |
fpag <- do_forced_paginate(obj) |
1119 | 6x |
if(length(fpag) > 1) { |
1120 | 1x |
return(lapply(fpag, |
1121 | 1x |
diagnose_pagination, |
1122 | 1x |
page_type = page_type, |
1123 | 1x |
font_family = font_family, |
1124 | 1x |
font_size = font_size, |
1125 | 1x |
lineheight = lineheight, |
1126 | 1x |
landscape = landscape, |
1127 | 1x |
pg_width = pg_width, |
1128 | 1x |
pg_height = pg_height, |
1129 | 1x |
margins = margins, |
1130 | 1x |
lpp = lpp, |
1131 | 1x |
cpp = cpp, |
1132 | 1x |
tf_wrap = tf_wrap, |
1133 | 1x |
max_width = max_width, |
1134 | 1x |
colwidths = colwidths, |
1135 | 1x |
col_gap = col_gap, |
1136 | 1x |
min_siblings = min_siblings, |
1137 | 1x |
nosplitin = nosplitin)) |
1138 |
} |
|
1139 | ||
1140 | 5x |
mpf <- matrix_form(obj, TRUE) |
1141 | 5x |
msgres <- capture.output({tmp <- try(paginate_to_mpfs(obj, page_type = page_type, |
1142 | 5x |
font_family = font_family, |
1143 | 5x |
font_size = font_size, |
1144 | 5x |
lineheight = lineheight, |
1145 | 5x |
landscape = landscape, |
1146 | 5x |
pg_width = pg_width, |
1147 | 5x |
pg_height = pg_height, |
1148 | 5x |
margins = margins, |
1149 | 5x |
lpp = lpp, |
1150 | 5x |
cpp = cpp, |
1151 | 5x |
tf_wrap = tf_wrap, |
1152 | 5x |
max_width = max_width, |
1153 | 5x |
colwidths = colwidths, |
1154 | 5x |
col_gap = col_gap, |
1155 | 5x |
min_siblings = min_siblings, |
1156 | 5x |
nosplitin = nosplitin, |
1157 | 5x |
verbose = TRUE))}, |
1158 | 5x |
type = "message") |
1159 | 5x |
if(is(tmp, "try-error") && grepl("Width of row labels equal to or larger", tmp)) { |
1160 | ! |
cond <- attr(tmp, "condition") |
1161 | ! |
stop(conditionMessage(cond), call. = conditionCall(cond)) |
1162 |
} |
|
1163 | ||
1164 | 5x |
lpp_diagnostic <- grep("^(Determining lines|Lines per page available).*$", msgres, value = TRUE) |
1165 | 5x |
cpp_diagnostic <- unique(grep("^Adjusted characters per page.*$", msgres, value = TRUE)) |
1166 | ||
1167 | 5x |
mpf <- do_cell_fnotes_wrap(mpf, widths = colwidths, max_width = max_width, tf_wrap = tf_wrap) |
1168 | 5x |
mpf <- mpf_infer_cinfo(mpf, colwidths = colwidths) |
1169 | ||
1170 | 5x |
rownls <- grep("Checking pagination after row", msgres, fixed = TRUE) |
1171 | 5x |
rownum <- as.integer(gsub("[^[:digit:]]*(.*)$", "\\1", msgres[rownls])) |
1172 | 5x |
rowmsgs <- vapply(unique(rownum), function(ii) { |
1173 | ! |
idx <- max(which(rownum == ii)) |
1174 | ! |
gsub("\\t[.]*", "", msgres[rownls[idx] + 1]) |
1175 |
}, "") |
|
1176 | ||
1177 | 5x |
msgdf <- data.frame(abs_rownumber = unique(rownum), |
1178 | 5x |
final_pag_result = rowmsgs, stringsAsFactors = FALSE) |
1179 | 5x |
rdf <-mf_rinfo(mpf)[, c("abs_rownumber", "label", "self_extent", "par_extent", "node_class")] |
1180 | 5x |
rdf$pag_attempted <- rdf$abs_rownumber %in% rownum |
1181 | 5x |
row_diagnose <- merge(rdf, msgdf, by = "abs_rownumber", all.x = TRUE) |
1182 | ||
1183 | 5x |
colnls <- grep("Checking pagination after column", msgres, fixed = TRUE) |
1184 | 5x |
colnum <- as.integer(gsub("[^[:digit:]]*(.*)$", "\\1", msgres[colnls])) |
1185 | 5x |
colmsgs <- vapply(unique(colnum), function(ii) { |
1186 | ! |
idx <- max(which(colnum == ii)) |
1187 | ! |
gsub("\\t[.]*", "", msgres[colnls[idx] + 1]) |
1188 |
}, "") |
|
1189 | ||
1190 | 5x |
colmsgdf <- data.frame(abs_rownumber = unique(colnum), |
1191 | 5x |
final_pag_result = colmsgs, |
1192 | 5x |
stringsAsFactors = FALSE) |
1193 | 5x |
cdf <- mf_cinfo(mpf)[, c("abs_rownumber", "self_extent")] |
1194 | 5x |
cdf$pag_attempted <- cdf$abs_rownumber %in% colnum |
1195 | 5x |
col_diagnose <- merge(cdf, colmsgdf, by = "abs_rownumber", all.x = TRUE) |
1196 | 5x |
names(col_diagnose) <- gsub("^abs_rownumber$", "abs_colnumber", names(col_diagnose)) |
1197 | 5x |
list(lpp_diagnostics = lpp_diagnostic, |
1198 | 5x |
row_diagnostics = row_diagnose, |
1199 | 5x |
cpp_diagnostics = cpp_diagnostic, |
1200 | 5x |
col_diagnostics = col_diagnose) |
1201 |
} |
1 | ||
2 |
#' @importFrom htmltools tags tagList |
|
3 | ||
4 |
formats_1d <- c( |
|
5 |
"xx", "xx.", "xx.x", "xx.xx", "xx.xxx", "xx.xxxx", |
|
6 |
"xx%", "xx.%", "xx.x%", "xx.xx%", "xx.xxx%", "(N=xx)", ">999.9", ">999.99", |
|
7 |
"x.xxxx | (<0.0001)" |
|
8 |
) |
|
9 | ||
10 |
formats_2d <- c( |
|
11 |
"xx / xx", "xx. / xx.", "xx.x / xx.x", "xx.xx / xx.xx", "xx.xxx / xx.xxx", |
|
12 |
"N=xx (xx%)", "xx (xx%)", "xx (xx.%)", "xx (xx.x%)", "xx (xx.xx%)", |
|
13 |
"xx. (xx.%)", "xx.x (xx.x%)", "xx.xx (xx.xx%)", |
|
14 |
"(xx, xx)", "(xx., xx.)", "(xx.x, xx.x)", "(xx.xx, xx.xx)", |
|
15 |
"(xx.xxx, xx.xxx)", "(xx.xxxx, xx.xxxx)", |
|
16 |
"xx - xx", "xx.x - xx.x", "xx.xx - xx.xx", |
|
17 |
"xx (xx)", "xx. (xx.)", "xx.x (xx.x)", "xx.xx (xx.xx)", |
|
18 |
"xx (xx.)", "xx (xx.x)", "xx (xx.xx)", |
|
19 |
"xx.x, xx.x", |
|
20 |
"xx.x to xx.x" |
|
21 |
) |
|
22 | ||
23 |
formats_3d <- c( |
|
24 |
"xx. (xx. - xx.)", |
|
25 |
"xx.x (xx.x - xx.x)", |
|
26 |
"xx.xx (xx.xx - xx.xx)", |
|
27 |
"xx.xxx (xx.xxx - xx.xxx)" |
|
28 |
) |
|
29 | ||
30 |
#' @title List with currently supported formats and vertical alignments |
|
31 |
#' |
|
32 |
#' @description We support `xx` style format labels grouped by 1d, 2d and 3d. |
|
33 |
#' Currently valid format labels can not be added dynamically. Format functions |
|
34 |
#' must be used for special cases. |
|
35 |
#' |
|
36 |
#' @return |
|
37 |
#' * `list_valid_format_labels()`: A nested list, with elements listing the supported 1d, 2d, |
|
38 |
#' and 3d format strings. |
|
39 |
#' |
|
40 |
#' @examples |
|
41 |
#' list_valid_format_labels() |
|
42 |
#' |
|
43 |
#' @name list_formats |
|
44 |
#' @export |
|
45 |
list_valid_format_labels <- function() { |
|
46 | 54x |
structure( |
47 | 54x |
list( |
48 | 54x |
"1d" = formats_1d, |
49 | 54x |
"2d" = formats_2d, |
50 | 54x |
"3d" = formats_3d |
51 |
), |
|
52 | 54x |
info = "xx does not modify the element, and xx. rounds a number to 0 digits" |
53 |
) |
|
54 |
} |
|
55 |
#' @return |
|
56 |
#' * `list_valid_aligns()`: a character vector of valid vertical alignments |
|
57 |
#' |
|
58 |
#' @examples |
|
59 |
#' list_valid_aligns() |
|
60 |
#' |
|
61 |
#' @name list_formats |
|
62 |
#' @export |
|
63 |
list_valid_aligns <- function() { |
|
64 | 5475x |
c("left", "right", "center", "decimal", "dec_right", "dec_left") |
65 |
} |
|
66 | ||
67 |
#' @title Check if a format or alignment is supported |
|
68 |
#' |
|
69 |
#' @description Utility functions for checking formats and alignments. |
|
70 |
#' |
|
71 |
#' @param x either format string or an object returned by \code{sprintf_format} |
|
72 |
#' @param stop_otherwise logical, if \code{x} is not a format should an error be |
|
73 |
#' thrown |
|
74 |
#' |
|
75 |
#' @note No check if the function is actually a `formatter` is performed. |
|
76 |
#' |
|
77 |
#' @return |
|
78 |
#' * `is_valid_format`: \code{TRUE} if \code{x} is \code{NULL}, a supported |
|
79 |
#' format string, or a function; \code{FALSE} otherwise. |
|
80 |
#' |
|
81 |
#' @examples |
|
82 |
#' is_valid_format("xx.x") |
|
83 |
#' is_valid_format("fakeyfake") |
|
84 |
#' |
|
85 |
#' @name check_formats |
|
86 |
#' @export |
|
87 |
is_valid_format <- function(x, stop_otherwise = FALSE) { |
|
88 | 51x |
is_valid <- is.null(x) || |
89 | 51x |
(length(x) == 1 && |
90 | 51x |
(is.function(x) || |
91 | 51x |
x %in% unlist(list_valid_format_labels()))) |
92 | ||
93 | 51x |
if (stop_otherwise && !is_valid) { |
94 | ! |
stop("format needs to be a format label, sprintf_format object, a function, or NULL") |
95 |
} |
|
96 | ||
97 | 51x |
is_valid |
98 |
} |
|
99 |
#' @param algn vector of characters that indicates the requested cell alignments. |
|
100 |
#' |
|
101 |
#' @return |
|
102 |
#' * `check_aligns`: `TRUE` if it passes the check. |
|
103 |
#' |
|
104 |
#' @examples |
|
105 |
#' check_aligns(c("decimal", "dec_right")) |
|
106 |
#' |
|
107 |
#' @name check_formats |
|
108 |
#' @export |
|
109 |
check_aligns <- function(algn) { |
|
110 | ! |
if(anyNA(algn)) |
111 | ! |
stop("Got missing-value for text alignment.") |
112 | ! |
invalid <- setdiff(algn, list_valid_aligns()) |
113 | ! |
if(length(invalid) > 0) { |
114 | ! |
stop("Unsupported text-alignment(s): ", |
115 | ! |
paste(invalid, collapse = ", ")) |
116 |
} |
|
117 | ! |
invisible(TRUE) |
118 |
} |
|
119 | ||
120 |
#' Specify text format via a `sprintf` format string |
|
121 |
#' |
|
122 |
#' |
|
123 |
#' @param format character(1). A format string passed to `sprintf`. |
|
124 |
#' |
|
125 |
#' @export |
|
126 |
#' @return A formatting function which wraps and will apply the specified \code{printf} style format |
|
127 |
#' string \code{format}. |
|
128 |
#' @seealso \code{\link[base]{sprintf}} |
|
129 |
#' |
|
130 |
#' @examples |
|
131 |
#' |
|
132 |
#' fmtfun <- sprintf_format("(N=%i") |
|
133 |
#' format_value(100, format = fmtfun) |
|
134 |
#' |
|
135 |
#' fmtfun2 <- sprintf_format("%.4f - %.2f") |
|
136 |
#' format_value(list(12.23456, 2.724)) |
|
137 |
sprintf_format <- function(format) { |
|
138 | 1x |
function(x, ...) { |
139 | 1x |
do.call(sprintf, c(list(fmt = format), x)) |
140 |
} |
|
141 |
} |
|
142 | ||
143 | ||
144 |
#' Round and prepare a value for display |
|
145 |
#' |
|
146 |
#' This function is used within \code{\link{format_value}} to prepare numeric values within |
|
147 |
#' cells for formatting and display. |
|
148 |
#' |
|
149 |
#' @aliases rounding |
|
150 |
#' @param x numeric(1). Value to format |
|
151 |
#' @param digits numeric(1). Number of digits to round to, or \code{NA} to convert to a |
|
152 |
#' character value with no rounding. |
|
153 |
#' @param na_str character(1). The value to return if \code{x} is \code{NA}. |
|
154 |
#' |
|
155 |
#' @details |
|
156 |
#' This function combines the rounding behavior of R's standards-complaint |
|
157 |
#' \code{\link{round}} function (see the Details section of that documentation) |
|
158 |
#' with the strict decimal display of \code{\link{sprintf}}. The exact behavior |
|
159 |
#' is as follows: |
|
160 |
#' |
|
161 |
#' \enumerate{ |
|
162 |
#' \item{If \code{x} is NA, the value of \code{na_str} is returned} |
|
163 |
#' \item{If \code{x} is non-NA but \code{digits} is NA, \code{x} is converted to a character |
|
164 |
#' and returned} |
|
165 |
#' \item{If \code{x} and \code{digits} are both non-NA, \code{round} is called first, |
|
166 |
#' and then \code{sprintf} is used to convert the rounded value to a character with the |
|
167 |
#' appropriate number of trailing zeros enforced.} |
|
168 |
#' } |
|
169 |
#' |
|
170 |
#' @return A character value representing the value after rounding, containing |
|
171 |
#' containing any trailling zeros required to display \emph{exactly} \code{digits} |
|
172 |
#' elements. |
|
173 |
#' @note |
|
174 |
#' This differs from the base R \code{\link{round}} function in that \code{NA} |
|
175 |
#' digits indicate x should be passed converted to character and returned unchanged |
|
176 |
#' whereas \code{round(x, digits =NA)} returns \code{NA} for all values of \code{x}. |
|
177 |
#' |
|
178 |
#' This behavior will differ from \code{as.character(round(x, digits = digits))} |
|
179 |
#' in the case where there are not at least \code{digits} significant digits |
|
180 |
#' after the decimal that remain after rounding. It \emph{may} differ from |
|
181 |
#' \code{sprintf("\%.Nf", x)} for values ending in \code{5} after the decimal place |
|
182 |
#' on many popular operating systems due to \code{round}'s stricter adherence to the |
|
183 |
#' `IEC 60559` standard, particularly for R versions > 4.0.0 (see Warning in \code{\link[base:round]{round}} |
|
184 |
#' documentation). |
|
185 |
#' |
|
186 |
#' @export |
|
187 |
#' @seealso \code{link{format_value}} \code{\link[base:round]{round}} \code{\link[base:sprintf]{sprintf}} |
|
188 |
#' @examples |
|
189 |
#' |
|
190 |
#' round_fmt(0, digits = 3) |
|
191 |
#' round_fmt(.395, digits = 2) |
|
192 |
#' round_fmt(NA, digits = 1) |
|
193 |
#' round_fmt(NA, digits = 1, na_str = "-") |
|
194 |
#' round_fmt(2.765923, digits = NA) |
|
195 |
round_fmt <- function(x, digits, na_str = "NA") { |
|
196 | 193x |
if (!is.na(digits) && digits < 0) { |
197 | ! |
stop("round_fmt currentlyd does not support non-missing values of digits <0") |
198 |
} |
|
199 | 193x |
if (is.na(x)) { |
200 | 4x |
na_str |
201 | 189x |
} else if (is.na(digits)) { |
202 | 41x |
paste0(x) |
203 |
} else { |
|
204 | 148x |
sprfmt <- paste0("%.", digits, "f") |
205 | 148x |
sprintf(fmt = sprfmt, round(x, digits = digits)) |
206 |
} |
|
207 |
} |
|
208 | ||
209 | ||
210 | ||
211 |
val_pct_helper <- function(x, dig1, dig2, na_str, pct = TRUE) { |
|
212 | 32x |
if (pct) { |
213 | 18x |
x[2] <- x[2] * 100 |
214 |
} |
|
215 | 32x |
if (length(na_str) == 1) { |
216 | ! |
na_str <- rep(na_str, 2) |
217 |
} |
|
218 | 32x |
paste0( |
219 | 32x |
round_fmt(x[1], digits = dig1, na_str = na_str[1]), |
220 |
" (", |
|
221 | 32x |
round_fmt(x[2], digits = dig2, na_str = na_str[2]), |
222 | 32x |
if (pct) "%", ")" |
223 |
) |
|
224 |
} |
|
225 | ||
226 |
sep_2d_helper <- function(x, dig1, dig2, sep, na_str, wrap = NULL) { |
|
227 | 43x |
ret <- paste(mapply(round_fmt, x = x, digits = c(dig1, dig2), na_str = na_str), |
228 | 43x |
collapse = sep |
229 |
) |
|
230 | 43x |
if (!is.null(wrap)) { |
231 | 20x |
ret <- paste(c(wrap[1], ret, wrap[2]), collapse = "") |
232 |
} |
|
233 | 43x |
ret |
234 |
} |
|
235 | ||
236 |
## na_or_round <- function(x, digits, na_str) { |
|
237 |
## if(is.na(x)) |
|
238 |
## na_str |
|
239 |
## else |
|
240 |
## round(x, digits = digits) |
|
241 | ||
242 |
## } |
|
243 | ||
244 |
#' Converts a (possibly compound) value into a string using the \code{format} information |
|
245 |
#' |
|
246 |
#' @details A length-zero value for `na_str` will be interpreted as `"NA"`, as will any |
|
247 |
#' missing values within a non-length-zero `na_str` vector. |
|
248 |
#' |
|
249 |
#' @param x ANY. The value to be formatted |
|
250 |
#' @param format character(1) or function. The format label (string) or `formatter` function to apply to \code{x}. |
|
251 |
#' @param na_str character(1). String that should be displayed when the value of \code{x} is missing. |
|
252 |
#' Defaults to \code{"NA"}. |
|
253 |
#' @param output character(1). output type |
|
254 |
#' |
|
255 |
#' @return formatted text representing the cell \code{x}. |
|
256 |
#' @export |
|
257 |
#' |
|
258 |
#' @seealso [round_fmt()] |
|
259 |
#' @examples |
|
260 |
#' |
|
261 |
#' x <- format_value(pi, format = "xx.xx") |
|
262 |
#' x |
|
263 |
#' |
|
264 |
#' format_value(x, output = "ascii") |
|
265 |
#' |
|
266 |
format_value <- function(x, format = NULL, output = c("ascii", "html"), na_str = "NA") { |
|
267 |
## if(is(x, "CellValue")) |
|
268 |
## x = x[[1]] |
|
269 | ||
270 | 4711x |
if (length(x) == 0) { |
271 | 1x |
return("") |
272 |
} |
|
273 | ||
274 | 4710x |
output <- match.arg(output) |
275 | 4710x |
if (length(na_str) == 0) { |
276 | 1x |
na_str <- "NA" |
277 |
} |
|
278 | 4710x |
if (any(is.na(na_str))) { |
279 | 1x |
na_str[is.na(na_str)] <- "NA" |
280 |
} |
|
281 |
## format <- if (!missing(format)) format else obj_format(x) |
|
282 | ||
283 | ||
284 | 4710x |
txt <- if (all(is.na(x)) && length(na_str) == 1L) { |
285 | 21x |
na_str |
286 | 4710x |
} else if (is.null(format)) { |
287 | ! |
toString(x) |
288 | 4710x |
} else if (is.function(format)) { |
289 | 1x |
format(x, output = output) |
290 | 4710x |
} else if (is.character(format)) { |
291 | 4688x |
l <- if (format %in% formats_1d) { |
292 | 4610x |
1 |
293 | 4688x |
} else if (format %in% formats_2d) { |
294 | 69x |
2 |
295 | 4688x |
} else if (format %in% formats_3d) { |
296 | 8x |
3 |
297 |
} else { |
|
298 | 1x |
stop( |
299 | 1x |
"unknown format label: ", format, |
300 | 1x |
". use list_valid_format_labels() to get a list of all formats" |
301 |
) |
|
302 |
} |
|
303 | 4687x |
if (format != "xx" && length(x) != l) { |
304 | 2x |
stop( |
305 | 2x |
"cell <", paste(x), "> and format ", |
306 | 2x |
format, " are of different length" |
307 |
) |
|
308 |
} |
|
309 | 4685x |
if (length(na_str) < length(x)) { |
310 | 73x |
na_str <- rep(na_str, length.out = length(x)) |
311 |
} |
|
312 | 4685x |
switch(format, |
313 | 4572x |
"xx" = as.character(x), |
314 | 3x |
"xx." = round_fmt(x, digits = 0, na_str = na_str), |
315 | 6x |
"xx.x" = round_fmt(x, digits = 1, na_str = na_str), |
316 | 3x |
"xx.xx" = round_fmt(x, digits = 2, na_str = na_str), |
317 | 3x |
"xx.xxx" = round_fmt(x, digits = 3, na_str = na_str), |
318 | 3x |
"xx.xxxx" = round_fmt(x, digits = 4, na_str = na_str), |
319 | 2x |
"xx%" = paste0(round_fmt(x * 100, digits = NA, na_str = na_str), "%"), |
320 | 2x |
"xx.%" = paste0(round_fmt(x * 100, digits = 0, na_str = na_str), "%"), |
321 | 2x |
"xx.x%" = paste0(round_fmt(x * 100, digits = 1, na_str = na_str), "%"), |
322 | 2x |
"xx.xx%" = paste0(round_fmt(x * 100, digits = 2, na_str = na_str), "%"), |
323 | 2x |
"xx.xxx%" = paste0(round_fmt(x * 100, digits = 3, na_str = na_str), "%"), |
324 | 1x |
"(N=xx)" = paste0("(N=", round_fmt(x, digits = NA, na_str = na_str), ")"), |
325 | 3x |
">999.9" = ifelse(x > 999.9, ">999.9", round_fmt(x, digits = 1, na_str = na_str)), |
326 | 3x |
">999.99" = ifelse(x > 999.99, ">999.99", round_fmt(x, digits = 2, na_str = na_str)), |
327 | 3x |
"x.xxxx | (<0.0001)" = ifelse(x < 0.0001, "<0.0001", round_fmt(x, digits = 4, na_str = na_str)), |
328 | 2x |
"xx / xx" = sep_2d_helper(x, dig1 = NA, dig2 = NA, sep = " / ", na_str = na_str), |
329 | 2x |
"xx. / xx." = sep_2d_helper(x, dig1 = 0, dig2 = 0, sep = " / ", na_str = na_str), |
330 | 2x |
"xx.x / xx.x" = sep_2d_helper(x, dig1 = 1, dig2 = 1, sep = " / ", na_str = na_str), |
331 | 2x |
"xx.xx / xx.xx" = sep_2d_helper(x, dig1 = 2, dig2 = 2, sep = " / ", na_str = na_str), |
332 | 2x |
"xx.xxx / xx.xxx" = sep_2d_helper(x, dig1 = 3, dig2 = 3, sep = " / ", na_str = na_str), |
333 | 2x |
"N=xx (xx%)" = paste0("N=", val_pct_helper(x, dig1 = NA, dig2 = NA, na_str = na_str)), |
334 | 3x |
"xx (xx%)" = val_pct_helper(x, dig1 = NA, dig2 = NA, na_str = na_str), |
335 | 2x |
"xx (xx.%)" = val_pct_helper(x, dig1 = NA, dig2 = 0, na_str = na_str), |
336 | 2x |
"xx (xx.x%)" = val_pct_helper(x, dig1 = NA, dig2 = 1, na_str = na_str), |
337 | 2x |
"xx (xx.xx%)" = val_pct_helper(x, dig1 = NA, dig2 = 2, na_str = na_str), |
338 | 2x |
"xx. (xx.%)" = val_pct_helper(x, dig1 = 0, dig2 = 0, na_str = na_str), |
339 | 3x |
"xx.x (xx.x%)" = val_pct_helper(x, dig1 = 1, dig2 = 1, na_str = na_str), |
340 | 2x |
"xx.xx (xx.xx%)" = val_pct_helper(x, dig1 = 2, dig2 = 2, na_str = na_str), |
341 | 2x |
"(xx, xx)" = sep_2d_helper(x, |
342 | 2x |
dig1 = NA, dig2 = NA, sep = ", ", |
343 | 2x |
na_str = na_str, wrap = c("(", ")") |
344 |
), |
|
345 | 2x |
"(xx., xx.)" = sep_2d_helper(x, |
346 | 2x |
dig1 = 0, dig2 = 0, sep = ", ", |
347 | 2x |
na_str = na_str, wrap = c("(", ")") |
348 |
), |
|
349 | 2x |
"(xx.x, xx.x)" = sep_2d_helper(x, |
350 | 2x |
dig1 = 1, dig2 = 1, sep = ", ", |
351 | 2x |
na_str = na_str, wrap = c("(", ")") |
352 |
), |
|
353 | 2x |
"(xx.xx, xx.xx)" = sep_2d_helper(x, |
354 | 2x |
dig1 = 2, dig2 = 2, sep = ", ", |
355 | 2x |
na_str = na_str, wrap = c("(", ")") |
356 |
), |
|
357 | 2x |
"(xx.xxx, xx.xxx)" = sep_2d_helper(x, |
358 | 2x |
dig1 = 3, dig2 = 3, sep = ", ", |
359 | 2x |
na_str = na_str, wrap = c("(", ")") |
360 |
), |
|
361 | 2x |
"(xx.xxxx, xx.xxxx)" = sep_2d_helper(x, |
362 | 2x |
dig1 = 4, dig2 = 4, sep = ", ", |
363 | 2x |
na_str = na_str, wrap = c("(", ")") |
364 |
), |
|
365 | 2x |
"xx - xx" = sep_2d_helper(x, dig1 = NA, dig2 = NA, sep = " - ", na_str = na_str), |
366 | 5x |
"xx.x - xx.x" = sep_2d_helper(x, dig1 = 1, dig2 = 1, sep = " - ", na_str = na_str), |
367 | 2x |
"xx.xx - xx.xx" = sep_2d_helper(x, dig1 = 2, dig2 = 2, sep = " - ", na_str = na_str), |
368 | 2x |
"xx (xx)" = val_pct_helper(x, dig1 = NA, dig2 = NA, na_str = na_str, pct = FALSE), |
369 | 2x |
"xx. (xx.)" = val_pct_helper(x, dig1 = 0, dig2 = 0, na_str = na_str, pct = FALSE), |
370 | 2x |
"xx.x (xx.x)" = val_pct_helper(x, dig1 = 1, dig2 = 1, na_str = na_str, pct = FALSE), |
371 | 2x |
"xx.xx (xx.xx)" = val_pct_helper(x, dig1 = 2, dig2 = 2, na_str = na_str, pct = FALSE), |
372 | 2x |
"xx (xx.)" = val_pct_helper(x, dig1 = NA, dig2 = 0, na_str = na_str, pct = FALSE), |
373 | 2x |
"xx (xx.x)" = val_pct_helper(x, dig1 = NA, dig2 = 1, na_str = na_str, pct = FALSE), |
374 | 2x |
"xx (xx.xx)" = val_pct_helper(x, dig1 = NA, dig2 = 2, na_str = na_str, pct = FALSE), |
375 | 2x |
"xx.x, xx.x" = sep_2d_helper(x, dig1 = 1, dig2 = 1, sep = ", ", na_str = na_str), |
376 | 2x |
"xx.x to xx.x" = sep_2d_helper(x, dig1 = 1, dig2 = 1, sep = " to ", na_str = na_str), |
377 | 2x |
"xx.xx (xx.xx - xx.xx)" = paste0( |
378 | 2x |
round_fmt(x[1], digits = 2, na_str = na_str[1]), " ", |
379 | 2x |
sep_2d_helper(x[2:3], |
380 | 2x |
dig1 = 2, dig2 = 2, |
381 | 2x |
sep = " - ", na_str = na_str[2:3], |
382 | 2x |
wrap = c("(", ")") |
383 |
) |
|
384 |
), |
|
385 | 2x |
"xx. (xx. - xx.)" = paste0( |
386 | 2x |
round_fmt(x[1], digits = 0, na_str = na_str[1]), " ", |
387 | 2x |
sep_2d_helper(x[2:3], |
388 | 2x |
dig1 = 0, dig2 = 0, |
389 | 2x |
sep = " - ", na_str = na_str[2:3], |
390 | 2x |
wrap = c("(", ")") |
391 |
) |
|
392 |
), |
|
393 | 2x |
"xx.x (xx.x - xx.x)" = paste0( |
394 | 2x |
round_fmt(x[1], digits = 1, na_str = na_str[1]), " ", |
395 | 2x |
sep_2d_helper(x[2:3], |
396 | 2x |
dig1 = 1, dig2 = 1, |
397 | 2x |
sep = " - ", na_str = na_str[2:3], |
398 | 2x |
wrap = c("(", ")") |
399 |
) |
|
400 |
), |
|
401 | 2x |
"xx.xxx (xx.xxx - xx.xxx)" = paste0( |
402 | 2x |
round_fmt(x[1], digits = 3, na_str = na_str[1]), " ", |
403 | 2x |
sep_2d_helper(x[2:3], |
404 | 2x |
dig1 = 3, dig2 = 3, |
405 | 2x |
sep = " - ", na_str = na_str[2:3], |
406 | 2x |
wrap = c("(", ")") |
407 |
) |
|
408 |
), |
|
409 | ! |
paste("format string", format, "not found") |
410 |
) |
|
411 |
} |
|
412 | 4707x |
txt[is.na(txt)] <- na_str |
413 | 4707x |
if (output == "ascii") { |
414 | 4706x |
txt |
415 | 1x |
} else if (output == "html") { |
416 |
## convert to tagList |
|
417 |
## convert \n to <br/> |
|
418 | ||
419 | 1x |
if (identical(txt, "")) { |
420 | ! |
txt |
421 |
} else { |
|
422 | 1x |
els <- unlist(strsplit(txt, "\n", fixed = TRUE)) |
423 | 1x |
Map(function(el, is.last) { |
424 | 1x |
tagList(el, if (!is.last) tags$br() else NULL) |
425 | 1x |
}, els, c(rep(FALSE, length(els) - 1), TRUE)) |
426 |
} |
|
427 |
} else { |
|
428 | ! |
txt |
429 |
} |
|
430 |
} |
|
431 | ||
432 |
setClassUnion("FormatSpec", c("NULL", "character", "function", "list")) |
|
433 |
setClassUnion("characterOrNULL", c("NULL", "character")) |
|
434 |
setClass("fmt_config", |
|
435 |
slots = c(format = "FormatSpec", |
|
436 |
format_na_str = "characterOrNULL", |
|
437 |
align = "characterOrNULL")) |
|
438 | ||
439 |
#' Format Configuration |
|
440 |
#' |
|
441 |
#' @param format character(1) or function. A format label (string) or `formatter` function. |
|
442 |
#' @param na_str character(1). String that should be displayed in place of missing values. |
|
443 |
#' @param align character(1). Alignment values should be rendered with. |
|
444 |
#' |
|
445 |
#' @return An object of class `fmt_config` which contains the following elements: |
|
446 |
#' * `format` |
|
447 |
#' * `na_str` |
|
448 |
#' * `align` |
|
449 |
#' |
|
450 |
#' @examples |
|
451 |
#' fmt_config(format = "xx.xx", na_str = "-", align = "left") |
|
452 |
#' fmt_config(format = "xx.xx - xx.xx", align = "right") |
|
453 |
#' |
|
454 |
#' @export |
|
455 |
fmt_config <- function(format = NULL, na_str = "NA", align = "center") { |
|
456 | 2x |
new("fmt_config", format = format, format_na_str = na_str, align = align) |
457 |
} |
1 |
#' @import grid |
|
2 |
#' @import grDevices |
|
3 |
NULL |
|
4 |
## https://www.ietf.org/rfc/rfc0678.txt |
|
5 | ||
6 |
## This assumes fixed font size, monospaced font |
|
7 | ||
8 |
std_cpi <- 10L |
|
9 |
std_lpi <- 6L |
|
10 | ||
11 | ||
12 |
std_full_pg_wd_in <- 8.5 |
|
13 | ||
14 |
std_full_pg_ht_in <- 11 |
|
15 | ||
16 |
std_log_pg_wd_chars <- 72 |
|
17 | ||
18 |
std_log_pg_ht_lines <- 60 |
|
19 | ||
20 |
std_marg_ht <- round((std_full_pg_ht_in - std_log_pg_ht_lines / std_lpi) / 2, 2) |
|
21 |
std_marg_wd <- round((std_full_pg_wd_in - std_log_pg_wd_chars / std_cpi) / 2, 2) |
|
22 | ||
23 |
std_margins <- list( |
|
24 |
top = std_marg_ht, |
|
25 |
bottom = std_marg_ht, |
|
26 |
left = std_marg_wd, |
|
27 |
right = std_marg_wd |
|
28 |
) |
|
29 | ||
30 |
## does not appear to be used anywhere |
|
31 |
## to_inches_num <- function(x) { |
|
32 |
## if (is(x, "unit")) { |
|
33 |
## x <- unclass(convertUnit(x, "inches")) |
|
34 |
## } |
|
35 |
## x |
|
36 |
## } |
|
37 | ||
38 |
## Physical size, does not take margins into account |
|
39 |
pg_dim_names <- list( |
|
40 |
letter = c(8.5, 11), |
|
41 |
a4 = c(8.27, 11.69), |
|
42 |
legal = c(8.5, 14) |
|
43 |
) |
|
44 | ||
45 | ||
46 |
#' |
|
47 |
#' Supported Named Page `TypesList` supported named page types |
|
48 |
#' |
|
49 |
#' @return for `page_types` a character vector of supported page types, |
|
50 |
#' for `page_dim` the dimensions (width, then height) of the selected page type. |
|
51 |
#' |
|
52 |
#' @export |
|
53 |
#' @examples |
|
54 |
#' page_types() |
|
55 |
#' page_dim("a4") |
|
56 |
page_types <- function() { |
|
57 | 35x |
names(pg_dim_names) |
58 |
} |
|
59 | ||
60 |
#' @export |
|
61 |
#' @param page_type character(1). The name of a page size specification. Call |
|
62 |
#' `page_types` for supported values. |
|
63 |
#' @rdname page_types |
|
64 |
page_dim <- function(page_type) { |
|
65 | 11x |
if (is.null(page_type)) { |
66 | 6x |
return(NULL) |
67 |
} |
|
68 | 5x |
if (!page_type %in% page_types()) { |
69 | 1x |
stop("Unrecognized page-size specification: ", page_type) |
70 |
} |
|
71 | 4x |
pg_dim_names[[page_type]] |
72 |
} |
|
73 | ||
74 | ||
75 | ||
76 |
#' Calculate lines per inch and characters per inch for font |
|
77 |
#' |
|
78 |
#' @inheritParams page_lcpp |
|
79 |
#' |
|
80 |
#' @details This function creates opens pdf graphics device writing to an temporary file, |
|
81 |
#' then utilizes [grid::convertWidth()] and [grid::convertHeight()] to calculate |
|
82 |
#' lines per inch and characters per inch for the specified font family, size, and |
|
83 |
#' line height. |
|
84 |
#' |
|
85 |
#' An error is thrown if the font is not monospaced (determined by comparing |
|
86 |
#' the effective widths of the `M` and `.` glyphs). |
|
87 |
#' @return named list with `cpi` and `lpi`, the characters and lines per |
|
88 |
#' inch, respectively. |
|
89 |
#' |
|
90 |
#' @export |
|
91 |
#' @examples |
|
92 |
#' font_lcpi() |
|
93 |
#' |
|
94 |
#' font_lcpi(font_size = 8) |
|
95 |
#' |
|
96 |
#' font_lcpi(font_size = 8, lineheight = 1.1) |
|
97 |
font_lcpi <- function(font_family = "Courier", font_size = 8, lineheight = 1) { |
|
98 | 26x |
tmppdf <- tempfile(fileext = ".pdf") |
99 | 26x |
pdf(tmppdf) |
100 | 26x |
on.exit(dev.off()) |
101 | 26x |
grid.newpage() |
102 | 26x |
gp <- gpar(fontfamily = font_family, fontsize = font_size, lineheight = lineheight) |
103 | 26x |
pushViewport(plotViewport(gp = gp)) |
104 | 26x |
if (convertWidth(unit(1, "strwidth", "."), "inches", valueOnly = TRUE) != |
105 | 26x |
convertWidth(unit(1, "strwidth", "M"), "inches", valueOnly = TRUE)) { |
106 | 1x |
stop( |
107 | 1x |
"The font family you selected - ", |
108 | 1x |
font_family, |
109 | 1x |
" - does not appear to be monospaced. This is not supported." |
110 |
) |
|
111 |
} |
|
112 | 25x |
list( |
113 | 25x |
cpi = 1 / convertWidth(unit(1, "strwidth", "h"), "inches", valueOnly = TRUE), |
114 | 25x |
lpi = convertHeight(unit(1, "inches"), "lines", valueOnly = TRUE) |
115 |
) |
|
116 |
} |
|
117 | ||
118 |
marg_order <- c("bottom", "left", "top", "right") |
|
119 | ||
120 |
#' Determine lines per page (`LPP`) and characters per page (`CPP`) based on font and page type |
|
121 |
#' |
|
122 |
#' @param page_type character(1). Name of a page type. See |
|
123 |
#' `page_types`. Ignored when `pg_width` and `pg_height` |
|
124 |
#' are set directly. |
|
125 |
#' @param landscape logical(1). Should the dimensions of `page_type` |
|
126 |
#' be inverted for landscape? Defaults to `FALSE`, ignored when |
|
127 |
#' `pg_width` and `pg_height` are set directly. |
|
128 |
#' @param font_family character(1). Name of a font family. An error |
|
129 |
#' will be thrown if the family named is not monospaced. Defaults |
|
130 |
#' to Courier. |
|
131 |
#' @param font_size numeric(1). Font size, defaults to 12. |
|
132 |
#' @param lineheight numeric(1). Line height, defaults to 1. |
|
133 |
#' @param margins numeric(4). Named numeric vector containing `'bottom'`, |
|
134 |
#' `'left'`, `'top'`, and `'right'` margins in inches. Defaults |
|
135 |
#' to `.5` inches for both vertical margins and `.75` for both |
|
136 |
#' horizontal margins. |
|
137 |
#' @param pg_width numeric(1). Page width in inches. |
|
138 |
#' @param pg_height numeric(1). Page height in inches. |
|
139 |
#' |
|
140 |
#' @return a named list containing `LPP` (lines per page) and `CPP` (characters per page) |
|
141 |
#' elements suitable for use by the pagination machinery. |
|
142 |
#' |
|
143 |
#' @export |
|
144 |
#' @examples |
|
145 |
#' page_lcpp() |
|
146 |
#' page_lcpp(font_size = 10) |
|
147 |
#' page_lcpp("a4", font_size = 10) |
|
148 |
#' |
|
149 |
#' page_lcpp(margins = c(top = 1, bottom = 1, left = 1, right = 1)) |
|
150 |
#' page_lcpp(pg_width = 10, pg_height = 15) |
|
151 |
page_lcpp <- function(page_type = page_types(), |
|
152 |
landscape = FALSE, |
|
153 |
font_family = "Courier", |
|
154 |
font_size = 8, |
|
155 |
lineheight = 1, |
|
156 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
157 |
pg_width = NULL, |
|
158 |
pg_height = NULL) { |
|
159 | 26x |
if(is.null(page_type)) |
160 | 4x |
page_type <- page_types()[1] |
161 |
else |
|
162 | 22x |
page_type <- match.arg(page_type) |
163 | ||
164 | 26x |
if(is.null(names(margins))) |
165 | 6x |
names(margins) <- marg_order |
166 |
else |
|
167 | 20x |
margins <- margins[marg_order] |
168 | 26x |
if(any(is.na(margins))) |
169 | ! |
stop("margins argument must have names 'bottom', 'left', 'top' and 'right'.") |
170 | 26x |
lcpi <- font_lcpi( |
171 | 26x |
font_family = font_family, |
172 | 26x |
font_size = font_size, |
173 | 26x |
lineheight = lineheight |
174 |
) |
|
175 | ||
176 | 25x |
wdpos <- ifelse(landscape, 2, 1) |
177 | 25x |
pg_width <- pg_width %||% pg_dim_names[[page_type]][wdpos] |
178 | 25x |
pg_height <- pg_height %||% pg_dim_names[[page_type]][-wdpos] |
179 | ||
180 | 25x |
pg_width <- pg_width - sum(margins[c("left", "right")]) |
181 | 25x |
pg_height <- pg_height - sum(margins[c("top", "bottom")]) |
182 | ||
183 | 25x |
list( |
184 | 25x |
cpp = floor(lcpi[["cpi"]] * pg_width), |
185 | 25x |
lpp = floor(lcpi[["lpi"]] * pg_height) |
186 |
) |
|
187 |
} |
|
188 | ||
189 |
## pg_types <- list( |
|
190 |
## "fsrp" = c(cpp = 110, lpp = 66), |
|
191 |
## "fsrp8" = c(cpp = 110, lpp = 66), |
|
192 |
## "fsrp7" = c(cpp = 110, lpp = 75), |
|
193 |
## "fsrl" = c(cpp = 149, lpp = 51), |
|
194 |
## "fsrl8" = c(cpp = 149, lpp = 51), |
|
195 |
## "fsrl7" = c(cpp = 150, lpp = 59), |
|
196 |
## "erp" = c(cpp = 96, lpp = 66), |
|
197 |
## "erp8" = c(cpp = 96, lpp = 66), |
|
198 |
## "erl" = c(cpp = 149, lpp = 45), |
|
199 |
## "erl8" = c(cpp = 149, lpp = 45), |
|
200 |
## "sasp" = c(cpp = 93, lpp = 73), |
|
201 |
## "sasp8" = c(cpp = 93, lpp = 73), |
|
202 |
## "sasl" = c(cpp = 134, lpp = 52), |
|
203 |
## "sasl8" = c(cpp = 134, lpp = 52), |
|
204 |
## "sasp7" = c(cpp = 107, lpp = 92), |
|
205 |
## "sasl7" = c(cpp = 154, lpp = 64), |
|
206 |
## "sasp6" = c(cpp = 125, lpp = 108), |
|
207 |
## "sasl6" = c(cpp = 180, lpp = 75), |
|
208 |
## "sasp10" = c(cpp = 78, lpp = 64), |
|
209 |
## "sasl10" = c(cpp = 108, lpp = 45), |
|
210 |
## "sasp9" = c(cpp = 87, lpp = 71), |
|
211 |
## "sasl9" = c(cpp = 120, lpp = 51), |
|
212 |
## "rapidp10" = c(cpp = 78, lpp = 64), |
|
213 |
## "rapidl10" = c(cpp = 108, lpp = 45), |
|
214 |
## "rapidp9" = c(cpp = 87, lpp = 71), |
|
215 |
## "rapidl9" = c(cpp = 120, lpp = 51), |
|
216 |
## "rapidp" = c(cpp = 93, lpp = 73), |
|
217 |
## "rapidp8" = c(cpp = 93, lpp = 73), |
|
218 |
## "rapidl" = c(cpp = 134, lpp = 52), |
|
219 |
## "rapidl8" = c(cpp = 134, lpp = 52), |
|
220 |
## "rapidp7" = c(cpp = 107, lpp = 92), |
|
221 |
## "rapidl7" = c(cpp = 154, lpp = 64), |
|
222 |
## "rapidp6" = c(cpp = 125, lpp = 108), |
|
223 |
## "rapidl6" = c(cpp = 180, lpp = 75), |
|
224 |
## "shibal" = c(cpp = 170, lpp = 48), |
|
225 |
## "shibal10" = c(cpp = 137, lpp = 39), |
|
226 |
## "shibal8" = c(cpp = 170, lpp = 48), |
|
227 |
## "shibal7" = c(cpp = 194, lpp = 56), |
|
228 |
## "shibal6" = c(cpp = 225, lpp = 65), |
|
229 |
## "shibap" = c(cpp = 112, lpp = 78), |
|
230 |
## "shibap10" = c(cpp = 89, lpp = 64), |
|
231 |
## "shibap8" = c(cpp = 112, lpp = 78), |
|
232 |
## "shibap7" = c(cpp = 127, lpp = 92), |
|
233 |
## "shibap6" = c(cpp = 148, lpp = 108)) |
|
234 | ||
235 | ||
236 | ||
237 | ||
238 | ||
239 | ||
240 |
## courier_fontsize_lcpi_df <- tribble( |
|
241 |
## ~courier_size, ~cpi, ~lpi, |
|
242 |
## 6, floor(129 / pg_dim_names[["letter"]][1]), floor(85 / pg_dim_names[["letter"]][2]), |
|
243 |
## 7, floor(110 / pg_dim_names[["letter"]][1]), floor(76 / pg_dim_names[["letter"]][2]), |
|
244 |
## 8, floor(95 / pg_dim_names[["letter"]][1]), floor(68 / pg_dim_names[["letter"]][2]), |
|
245 |
## 9, floor(84 / pg_dim_names[["letter"]][1]), floor(61 / pg_dim_names[["letter"]][2]), |
|
246 |
## 10, floor(75 / pg_dim_names[["letter"]][1]), floor(56 / pg_dim_names[["letter"]][2]) |
|
247 |
## ) |
|
248 | ||
249 |
## courier_lcpi <- function(size) { |
|
250 |
## grid.newpage() |
|
251 |
## gp <- gpar(fontfamily="Courier New", fontsize = size, lineheight = 1) |
|
252 |
## pushViewport(plotViewport( gp = gp)) |
|
253 |
## list(cpi = round(1/convertWidth(unit(1, "strwidth", "h"), "inches", valueOnly = TRUE), 0), |
|
254 |
## lpi = round(convertHeight(unit(1, "inches"), "lines", valueOnly = TRUE), 0)) |
|
255 |
## } |
1 |
## this can't be tested from within R |
|
2 |
# nocov start |
|
3 |
#' @importFrom stats na.omit |
|
4 |
#' @importFrom utils head tail localeToCharset |
|
5 |
#' @import checkmate |
|
6 | ||
7 |
d_hsep_factory <- function() { |
|
8 |
warn_sent <- FALSE |
|
9 |
function() { |
|
10 |
if (any(grepl("^UTF", localeToCharset()))) { |
|
11 |
"\u2014" |
|
12 |
} else { |
|
13 |
if (!warn_sent && interactive()) { |
|
14 |
message( |
|
15 |
"Detected non-UTF charset. Falling back to '-' ", |
|
16 |
"as default header/body separator. This warning ", |
|
17 |
"will only be shown once per R session." |
|
18 |
) |
|
19 |
warn_sent <<- TRUE |
|
20 |
} |
|
21 |
"-" |
|
22 |
} |
|
23 |
} |
|
24 |
} |
|
25 | ||
26 |
#' Default horizontal Separator |
|
27 |
#' |
|
28 |
#' The default horizontal separator character which can be |
|
29 |
#' displayed in the current `charset` for use in rendering table-likes. |
|
30 |
#' |
|
31 |
#' @return `unicode` 2014 (long dash for generating solid horizontal line) |
|
32 |
#' if in a locale that uses a UTF character set, otherwise an ASCII hyphen |
|
33 |
#' with a once-per-session warning. |
|
34 |
#' |
|
35 |
#' @export |
|
36 |
#' @examples |
|
37 |
#' default_hsep() |
|
38 |
default_hsep <- d_hsep_factory() |
|
39 | ||
40 |
# nocov end |
|
41 | ||
42 |
.calc_cell_widths <- function(mat, colwidths, col_gap) { |
|
43 | 147x |
spans <- mat$spans |
44 | 147x |
keep_mat <- mat$display |
45 | 147x |
body <- mat$strings |
46 | ||
47 | 147x |
nr <- nrow(body) |
48 | ||
49 | 147x |
cell_widths_mat <- matrix(rep(colwidths, nr), nrow = nr, byrow = TRUE) |
50 | 147x |
nc <- ncol(cell_widths_mat) |
51 | ||
52 | 147x |
for (i in seq_len(nrow(body))) { |
53 | 2730x |
if (any(!keep_mat[i, ])) { # any spans? |
54 | 6x |
j <- 1 |
55 | 6x |
while (j <= nc) { |
56 | 10x |
nj <- spans[i, j] |
57 | 10x |
j <- if (nj > 1) { |
58 | 6x |
js <- seq(j, j + nj - 1) |
59 | 6x |
cell_widths_mat[i, js] <- sum(cell_widths_mat[i, js]) + col_gap * (nj - 1) |
60 | 6x |
j + nj |
61 |
} else { |
|
62 | 4x |
j + 1 |
63 |
} |
|
64 |
} |
|
65 |
} |
|
66 |
} |
|
67 | 147x |
cell_widths_mat |
68 |
} |
|
69 | ||
70 | ||
71 |
# Main function that does the wrapping |
|
72 |
do_cell_fnotes_wrap <- function(mat, widths, max_width, tf_wrap) { |
|
73 | ||
74 | 87x |
col_gap <- mf_colgap(mat) |
75 | 87x |
ncchar <- sum(widths) + (length(widths) - 1) * col_gap |
76 | 87x |
inset <- table_inset(mat) |
77 | ||
78 |
## Text wrapping checks |
|
79 | 87x |
if (tf_wrap) { |
80 | 19x |
if (is.null(max_width)) { |
81 | 3x |
max_width <- getOption("width", 80L) |
82 | 16x |
} else if (is.character(max_width) && identical(max_width, "auto")) { |
83 | ! |
max_width <- ncchar + inset |
84 |
} |
|
85 | 19x |
assert_number(max_width, lower = 0) |
86 |
} |
|
87 | ||
88 |
## Check for having the right number of widths |
|
89 | 87x |
stopifnot(length(widths) == ncol(mat$strings)) |
90 | ||
91 |
## format the to ASCII |
|
92 | 87x |
cell_widths_mat <- .calc_cell_widths(mat, widths, col_gap) |
93 | ||
94 |
# Check that indentation is correct (it works only for body) |
|
95 | 87x |
.check_indentation(mat, row_col_width = cell_widths_mat[ , 1, drop = TRUE]) |
96 | 85x |
mod_ind_list <- .modify_indentation(mat, cell_widths_mat, do_what = "remove") |
97 | 85x |
mfs <- mod_ind_list[["mfs"]] |
98 | 85x |
cell_widths_mat <- mod_ind_list[["cell_widths_mat"]] |
99 | ||
100 |
# Main wrapper |
|
101 | 85x |
mf_strings(mat) <- matrix( |
102 | 85x |
unlist(mapply(wrap_string, |
103 | 85x |
str = mfs, |
104 | 85x |
width = cell_widths_mat, |
105 | 85x |
collapse = "\n" |
106 |
)), |
|
107 | 85x |
ncol = ncol(mfs) |
108 |
) |
|
109 | ||
110 |
## XXXXX this is wrong and will break for listings cause we don't know when |
|
111 |
## we need has_topleft to be FALSE!!!!!!!!!! |
|
112 | 85x |
mat <- mform_handle_newlines(mat) |
113 | ||
114 |
## this updates extents in rinfo AND nlines in ref_fnotes_df |
|
115 | 85x |
mat <- update_mf_nlines(mat, max_width = max_width) |
116 | ||
117 |
# Re-indenting |
|
118 | 85x |
mf_strings(mat) <- .modify_indentation(mat, cell_widths_mat, do_what = "add")[["mfs"]] |
119 | 85x |
.check_indentation(mat) # all went well |
120 | ||
121 | 85x |
mat |
122 |
} |
|
123 | ||
124 |
# Helper function to see if body indentation matches (minimum) |
|
125 |
# It sees if there is AT LEAST the indentation contained in rinfo |
|
126 |
.check_indentation <- function(mat, row_col_width = NULL) { |
|
127 |
# mf_nrheader(mat) # not useful |
|
128 | 173x |
mf_nlh <- mf_nlheader(mat) |
129 | 173x |
mf_lgrp <- mf_lgrouping(mat) |
130 | 173x |
mf_str <- mf_strings(mat) |
131 |
# we base everything on the groupings -> unique indentation identifiers |
|
132 | 173x |
if (!is.null(mf_rinfo(mat))) { # this happens in rare cases with rtables::rtable() |
133 | 173x |
mf_ind <- c(rep(0, mf_nrheader(mat)), mf_rinfo(mat)$indent) # XXX to fix with topleft |
134 |
} else { |
|
135 | ! |
mf_ind <- rep(0, mf_nrheader(mat)) |
136 |
} |
|
137 | 173x |
ind_std <- paste0(rep(" ", mat$indent_size), collapse = "") |
138 | ||
139 |
# Expected indent (-x negative numbers should not appear at this stage) |
|
140 | 173x |
stopifnot(all(mf_ind >= 0)) |
141 | 173x |
real_indent <- vapply(mf_ind, function(ii) { |
142 | 3254x |
paste0(rep(ind_std, ii), collapse = "") |
143 | 173x |
}, character(1)) |
144 | ||
145 | 173x |
if (!is.null(row_col_width) && |
146 | 173x |
any(row_col_width > 0) |
147 | 173x |
&& !is.null(mf_rinfo(mat))) { # third is rare case |
148 |
# Self consistency test for row_col_width (same groups should have same width) |
|
149 |
# This should not be necessary (nocov) |
|
150 | 87x |
consistency_check <- vapply(unique(mf_lgrp), function(ii) { |
151 | 1642x |
width_per_grp <- row_col_width[which(mf_lgrp == ii)] |
152 | 1642x |
all(width_per_grp == width_per_grp[1]) |
153 | 87x |
}, logical(1)) |
154 | 87x |
stopifnot(all(consistency_check)) |
155 | ||
156 |
# Taking only one width for each indentation grouping |
|
157 | 87x |
unique_row_col_width <- row_col_width[match(unique(mf_lgrp), mf_lgrp)] |
158 | ||
159 |
# Exception for check: case with summarize_row_groups and (hence) content_rows |
|
160 | 87x |
nchar_real_indent <- nchar(real_indent) |
161 | 87x |
body_rows <- seq(mf_nrheader(mat) + 1, length(nchar_real_indent)) |
162 | 87x |
nchar_real_indent[body_rows] <- nchar_real_indent[body_rows] + |
163 | 87x |
as.numeric(mf_rinfo(mat)$node_class != "ContentRow") |
164 |
# xxx I think all of the above is a bit buggy honestly (check ContentRows!!!) |
|
165 | ||
166 | 87x |
if (any(nchar_real_indent > unique_row_col_width)) { |
167 | 1x |
stop("Inserted width for row label column is not wide enough. ", |
168 | 1x |
"We found the following rows that do not have at least indentation * ind_size + 1", |
169 | 1x |
" characters to allow text to be shown after indentation: ", |
170 | 1x |
paste0(which(nchar(real_indent) + 1 > unique_row_col_width), collapse = " ")) |
171 |
} |
|
172 |
} |
|
173 | ||
174 |
# Main detector |
|
175 | 172x |
correct_indentation <- vapply(seq_along(mf_lgrp), function(xx) { |
176 | 3624x |
grouping <- mf_lgrp[xx] |
177 | 3624x |
if (nzchar(real_indent[grouping])) { |
178 | 27x |
has_correct_indentation <- stringi::stri_detect( |
179 | 27x |
mf_str[xx, 1], |
180 | 27x |
regex = paste0("^", real_indent[grouping]) |
181 |
) |
|
182 | 27x |
return(has_correct_indentation || !nzchar(mf_str[xx, 1])) # "" is still an ok indentation |
183 |
} |
|
184 |
# Cases where no indent are true by definition |
|
185 | 3597x |
return(TRUE) |
186 | 172x |
}, logical(1)) |
187 | ||
188 | 172x |
if (any(!correct_indentation)) { |
189 | 1x |
stop("We discovered indentation mismatches between the matrix_form and the indentation", |
190 | 1x |
" predefined in mf_rinfo. This should not happen. Contact the maintainer.") # nocov |
191 |
} |
|
192 |
} |
|
193 |
# Helper function that takes out or adds the proper indentation |
|
194 |
.modify_indentation <- function(mat, cell_widths_mat, do_what = c("remove", "add")) { |
|
195 |
# Extract info |
|
196 | 170x |
mfs <- mf_strings(mat) # we work on mfs |
197 | 170x |
mf_nlh <- mf_nlheader(mat) |
198 | 170x |
mf_l <- mf_lgrouping(mat) |
199 | 170x |
if (!is.null(mf_rinfo(mat))) { # this happens in rare cases with rtables::rtable() |
200 | 170x |
mf_ind <- c(rep(0, mf_nrheader(mat)), mf_rinfo(mat)$indent) # XXX to fix with topleft |
201 |
} else { |
|
202 | ! |
mf_ind <- rep(0, mf_nrheader(mat)) |
203 |
} |
|
204 | 170x |
stopifnot(length(mf_ind) == length(unique(mf_l))) # Check for indentation and grouping |
205 | 170x |
ind_std <- paste0(rep(" ", mat$indent_size), collapse = "") # standard size of indent 1 |
206 | ||
207 |
# Create real indentation |
|
208 | 170x |
real_indent <- sapply(mf_ind, function(ii) paste0(rep(ind_std, ii), collapse = "")) |
209 | ||
210 |
# Use groupings to add or remove proper indentation |
|
211 | 170x |
lbl_row <- mfs[, 1, drop = TRUE] |
212 | 170x |
for (ii in seq_along(lbl_row)) { |
213 | 3615x |
grp <- mf_l[ii] |
214 | 3615x |
if (nzchar(real_indent[grp])) { |
215 |
# Update also the widths!! |
|
216 | 23x |
if (do_what[1] == "remove") { |
217 | 6x |
cell_widths_mat[ii, 1] <- cell_widths_mat[ii, 1] - nchar(real_indent[grp]) |
218 | 6x |
mfs[ii, 1] <- stringi::stri_replace(lbl_row[ii], "", regex = paste0("^", real_indent[grp])) |
219 | 17x |
} else if (do_what[1] == "add") { |
220 | 17x |
mfs[ii, 1] <- paste0(real_indent[grp], lbl_row[ii]) |
221 |
} else { |
|
222 |
stop("do_what needs to be remove or add.") # nocov |
|
223 |
} |
|
224 |
} else { |
|
225 | 3592x |
mfs[ii, 1] <- lbl_row[ii] |
226 |
} |
|
227 |
} |
|
228 |
# Final return |
|
229 | 170x |
return(list("mfs" = mfs, "cell_widths_mat" = cell_widths_mat)) |
230 |
} |
|
231 | ||
232 | ||
233 |
## take a character vector and return whether the value is |
|
234 |
## a string version of a number or not |
|
235 |
is_number_str <- function(vec) { |
|
236 | ! |
is.na(as.numeric(vec)) |
237 |
} |
|
238 | ||
239 |
is_dec_align <- function(vec) { |
|
240 |
# "c" is not an alignment method we define in `formatters`, |
|
241 |
# but the reverse dependency package `tables` will need |
|
242 | 385x |
sdiff <- setdiff(vec, c(list_valid_aligns(), "c")) |
243 | 385x |
if(length(sdiff) > 0) |
244 | ! |
stop("Invalid text-alignment(s): ", |
245 | ! |
paste(sdiff, collapse = ", ")) |
246 | 385x |
grepl("dec", vec) |
247 |
} |
|
248 | ||
249 | 240x |
any_dec_align <- function(vec) any(is_dec_align(vec)) |
250 | ||
251 |
#' Decimal Alignment |
|
252 |
#' |
|
253 |
#' @description Aligning decimal values of string matrix. Allowed alignments are: `dec_left`, |
|
254 |
#' `dec_right` and `decimal`. |
|
255 |
#' |
|
256 |
#' @param string_mat character matrix. String matrix component of matrix print form object. |
|
257 |
#' @param align_mat character matrix. Aligns matrix component of matrix print form object. |
|
258 |
#' Should contain either `dec_left`, `dec_right` or `decimal` for values to be decimal aligned. |
|
259 |
#' |
|
260 |
#' @details Decimal alignment left and right (`dec_left` and `dec_right`) are different to |
|
261 |
#' center decimal alignment `decimal` only in the case some padding is present. This may |
|
262 |
#' happen if column widths are wider by setting parameters `widths` in `toString` or |
|
263 |
#' `colwidths` in `paginate_*` accordingly. It will be also the case (more common) of |
|
264 |
#' wider column names. Decimal alignment is not supported along with cell wrapping. |
|
265 |
#' |
|
266 |
#' @examples |
|
267 |
#' dfmf <- basic_matrix_form(mtcars[1:5,]) |
|
268 |
#' aligns <- mf_aligns(dfmf) |
|
269 |
#' aligns[, -c(1)] <- "dec_left" |
|
270 |
#' decimal_align(mf_strings(dfmf), aligns) |
|
271 |
#' |
|
272 |
#' @return Processed string matrix of matrix print form with decimal aligned values. |
|
273 |
#' |
|
274 |
#' @seealso [toString] and [MatrixPrintForm] |
|
275 |
#' |
|
276 |
#' @export |
|
277 |
decimal_align <- function(string_mat, align_mat) { |
|
278 |
## Evaluate if any values are to be decimal aligned |
|
279 | 45x |
if (!any_dec_align(align_mat)) { |
280 | ! |
return(string_mat) |
281 |
} |
|
282 | 45x |
for (i in seq(1, ncol(string_mat))) { |
283 |
## Take a column and its decimal alignments |
|
284 | 145x |
col_i <- as.character(string_mat[, i]) |
285 | 145x |
align_col_i <- is_dec_align(align_mat[, i]) |
286 | ||
287 |
## !( A || B) -> !A && !B DeMorgan's Law |
|
288 |
## Are there any values to be decimal aligned? safe if |
|
289 | 145x |
if (any(align_col_i) && any(!grepl("^[0-9]\\.", col_i))) { |
290 |
## Extract values not to be aligned (NAs, non-numbers, |
|
291 |
## doesn't say "decimal" in alignment matrix) |
|
292 |
## XXX FIXME because this happens after formatting, we can't tell the difference between |
|
293 |
## non-number strings which come from na_str+ NA value and strings which just aren't numbers. |
|
294 |
## this is a problem that should eventually be fixed. |
|
295 | 82x |
nas <- vapply(col_i, is.na, FUN.VALUE = logical(1)) |
296 | 82x |
nonnum <- !grepl("[0-9]", col_i) |
297 |
## No grepl("[a-zA-Z]", col_i) because this excludes N=xx, e.g. |
|
298 | 82x |
nonalign <- nas | nonnum | !align_col_i |
299 | 82x |
col_ia <- col_i[!nonalign] |
300 | ||
301 |
## Do decimal alignment |
|
302 | 82x |
if (length(col_ia) > 0) { |
303 |
# Special case: scientific notation |
|
304 | 82x |
has_sc_not <- grepl("\\d+[e|E][\\+|\\-]\\d+", col_ia) |
305 | 82x |
if(any(has_sc_not)) { |
306 | 1x |
stop("Found values using scientific notation between the ones that", |
307 | 1x |
" needs to be decimal aligned (aligns is decimal, dec_left or dec_right).", |
308 | 1x |
" Please consider using format functions to get a complete decimal ", |
309 | 1x |
"(e.g. formatC).") |
310 |
} |
|
311 | ||
312 |
## Count the number of numbers in the string |
|
313 | 81x |
matches <- gregexpr("\\d+\\.\\d+|\\d+", col_ia) |
314 | 81x |
more_than_one <- vapply(matches, function(x) { |
315 | 685x |
sum(attr(x, "match.length") > 0) > 1 |
316 | 81x |
}, logical(1)) |
317 |
## Throw error in case any have more than 1 numbers |
|
318 | 81x |
if (any(more_than_one)) { |
319 | 2x |
stop("Decimal alignment is not supported for multiple values. ", |
320 | 2x |
"Found the following string with multiple numbers ", |
321 | 2x |
"(first 3 selected from column ", col_i[1],"): '", |
322 | 2x |
paste0(col_ia[more_than_one][seq(1, 3)], |
323 | 2x |
collapse = "', '"), "'") |
324 |
} |
|
325 |
## General split (only one match -> the first) |
|
326 | 79x |
main_regexp <- regexpr("\\d+", col_ia) |
327 | 79x |
left <- regmatches(col_ia, main_regexp, invert = FALSE) |
328 | 79x |
right <- regmatches(col_ia, main_regexp, invert = TRUE) |
329 | 79x |
right <- sapply(right, "[[", 2) |
330 | 79x |
something_left <- sapply(strsplit(col_ia, "\\d+"), "[[", 1) |
331 | 79x |
left <- paste0(something_left, left) |
332 | 79x |
if (!checkmate::test_set_equal(paste0(left, right), col_ia)) |
333 | ! |
stop("Split string list lost some piece along the way. This ", |
334 | ! |
"should not have happened. Please contact the maintainer.") # nocov |
335 | 79x |
separator <- sapply(right, function(x) { |
336 | 639x |
if (nzchar(x)) { |
337 | 346x |
substr(x, 1, 1) |
338 |
} else { |
|
339 | 293x |
c(" ") |
340 |
} |
|
341 | 79x |
}, USE.NAMES = FALSE) |
342 | 79x |
right <- sapply(right, function(x) { |
343 | 639x |
if (nchar(x) > 1) { |
344 | 314x |
substr(x, 2, nchar(x)) |
345 |
} else { |
|
346 | 325x |
c("") |
347 |
} |
|
348 | 79x |
}, USE.NAMES = FALSE) |
349 |
## figure out whether we need space separators (at least one had a "." or not) |
|
350 | 79x |
if(!any(grepl("[^[:space:]]", separator))) |
351 | 26x |
separator <- gsub("[[:space:]]*", "", separator) |
352 |
## modify the piece with spaces |
|
353 | 79x |
left_mod <- paste0(spaces(max(nchar(left), na.rm = TRUE) - nchar(left)), left) |
354 | 79x |
right_mod <- paste0(right, spaces(max(nchar(right), na.rm = TRUE) - nchar(right))) |
355 |
# Put everything together |
|
356 | 79x |
aligned <- paste(left_mod, separator, right_mod, sep = "") |
357 | 79x |
string_mat[!nonalign, i] <- aligned |
358 |
} |
|
359 |
} |
|
360 |
} |
|
361 | 42x |
string_mat |
362 |
} |
|
363 | ||
364 |
# toString --------------------------------------------------------------------- |
|
365 |
# main printing code for MatrixPrintForm |
|
366 |
# |
|
367 | ||
368 |
#' @title Main printing system: `toString` |
|
369 |
#' |
|
370 |
#' @description |
|
371 |
#' All objects that are printed to console pass by `toString`. This function allows |
|
372 |
#' fundamental formatting specifications for the final output, like column widths and |
|
373 |
#' relative wrapping (`width`), title and footer wrapping (`tf_wrap = TRUE` and |
|
374 |
#' `max_width`), or horizontal separator character (e.g. `hsep = "+"`). |
|
375 |
#' |
|
376 |
#' @inheritParams MatrixPrintForm |
|
377 |
#' @param widths numeric (or NULL). (proposed) widths for the columns |
|
378 |
#' of \code{x}. The expected length of this numeric vector can be |
|
379 |
#' retrieved with `ncol() + 1` as the column of row names must |
|
380 |
#' also be considered. |
|
381 |
#' @param hsep character(1). Characters to repeat to create |
|
382 |
#' header/body separator line. |
|
383 |
#' @param tf_wrap logical(1). Should the texts for title, subtitle, |
|
384 |
#' and footnotes be wrapped? |
|
385 |
#' @param max_width integer(1), character(1) or NULL. Width that title |
|
386 |
#' and footer (including footnotes) materials should be |
|
387 |
#' word-wrapped to. If NULL, it is set to the current print width |
|
388 |
#' of the session (`getOption("width")`). If set to `"auto"`, |
|
389 |
#' the width of the table (plus any table inset) is used. Ignored |
|
390 |
#' completely if `tf_wrap` is `FALSE`. |
|
391 |
#' |
|
392 |
#' @details |
|
393 |
#' |
|
394 |
#' Manual insertion of newlines is not supported when `tf_wrap` is on |
|
395 |
#' and will result in a warning and undefined wrapping behavior. Passing |
|
396 |
#' vectors of already split strings remains supported, however in this |
|
397 |
#' case each string is word-wrapped separately with the behavior |
|
398 |
#' described above. |
|
399 |
#' |
|
400 |
#' @seealso [wrap_string()] |
|
401 |
#' |
|
402 |
#' @examples |
|
403 |
#' mform <- basic_matrix_form(mtcars) |
|
404 |
#' cat(toString(mform)) |
|
405 |
#' |
|
406 |
#' @return A character string containing the ASCII rendering |
|
407 |
#' of the table-like object represented by `x` |
|
408 |
#' |
|
409 |
#' @rdname tostring |
|
410 |
#' @exportMethod toString |
|
411 |
setMethod("toString", "MatrixPrintForm", function(x, |
|
412 |
widths = NULL, |
|
413 |
tf_wrap = FALSE, |
|
414 |
max_width = NULL, |
|
415 |
col_gap = mf_colgap(x), |
|
416 |
hsep = default_hsep()) { |
|
417 | 66x |
checkmate::assert_flag(tf_wrap) |
418 | ||
419 | 66x |
mat <- matrix_form(x, indent_rownames = TRUE) |
420 | ||
421 |
# Check for \n in mat strings -> if there are any, matrix_form did not work |
|
422 | 66x |
if (any(grepl("\n", mf_strings(mat)))) { |
423 | ! |
stop("Found newline characters (\\n) in string matrix produced by matrix_form. ", |
424 | ! |
"This is not supported and implies missbehavior on the first parsing (in matrix_form). ", |
425 | ! |
"Please contact the maintainer or file an issue.") # nocov |
426 |
} |
|
427 | ||
428 |
# Check that expansion worked for header -> should not happen |
|
429 | 66x |
if (!is.null(mf_rinfo(mat)) && # rare case of rtables::rtable() |
430 | 66x |
(length(mf_lgrouping(mat)) != nrow(mf_strings(mat)) || # non-unique grouping test |
431 | 66x |
mf_nrheader(mat) + nrow(mf_rinfo(mat)) != length(unique(mf_lgrouping(mat))))) { |
432 | ! |
stop("The sum of the expected nrows header and nrows of content table does ", |
433 | ! |
"not match the number of rows in the string matrix. To our knowledge, ", |
434 | ! |
"this is usually of a problem in solving newline characters (\\n) in the header. ", |
435 | ! |
"Please contact the maintaner or file an issue.") # nocov |
436 |
} |
|
437 | ||
438 | 66x |
inset <- table_inset(mat) |
439 | ||
440 |
# if cells are decimal aligned, run propose column widths |
|
441 |
# if the provided widths is less than proposed width, return an error |
|
442 | 66x |
if (any_dec_align(mf_aligns(mat))) { |
443 | 22x |
aligned <- propose_column_widths(x) |
444 | ||
445 |
# catch any columns that require widths more than what is provided |
|
446 | 20x |
if (!is.null(widths)) { |
447 | 9x |
how_wide <- sapply(seq_along(widths), function(i) c(widths[i] - aligned[i])) |
448 | 9x |
too_wide <- how_wide < 0 |
449 | 9x |
if (any(too_wide)) { |
450 | 2x |
desc_width <- paste(paste( |
451 | 2x |
names(which(too_wide)), |
452 | 2x |
paste0("(", how_wide[too_wide], ")") |
453 | 2x |
), collapse = ", ") |
454 | 2x |
stop( |
455 | 2x |
"Inserted width(s) for column(s) ", desc_width, |
456 | 2x |
" is(are) not wide enough for the desired alignment." |
457 |
) |
|
458 |
} |
|
459 |
} |
|
460 |
} |
|
461 | ||
462 |
# Column widths are fixed here |
|
463 | 62x |
if (is.null(widths)) { |
464 |
# if mf does not have widths -> propose them |
|
465 | 49x |
widths <- mf_col_widths(x) %||% propose_column_widths(x) |
466 |
} else { |
|
467 | 13x |
mf_col_widths(x) <- widths |
468 |
} |
|
469 | ||
470 |
# Total number of characters for the table |
|
471 | 62x |
ncchar <- sum(widths) + (length(widths) - 1) * col_gap |
472 | ||
473 |
## Text wrapping checks (widths) |
|
474 | 62x |
if (tf_wrap) { |
475 | 16x |
if (is.null(max_width)) { |
476 | 11x |
max_width <- getOption("width", 80L) |
477 | 5x |
} else if (is.character(max_width) && identical(max_width, "auto")) { |
478 | 2x |
max_width <- ncchar + inset |
479 |
} |
|
480 | 16x |
assert_number(max_width, lower = 0) |
481 |
} |
|
482 | ||
483 |
# Main wrapper function for table core |
|
484 | 62x |
mat <- do_cell_fnotes_wrap(mat, widths, max_width = max_width, tf_wrap = tf_wrap) |
485 | ||
486 | 60x |
body <- mf_strings(mat) |
487 | 60x |
aligns <- mf_aligns(mat) |
488 | 60x |
keep_mat <- mf_display(mat) |
489 |
## spans <- mat$spans |
|
490 |
## ri <- mat$row_info |
|
491 | 60x |
ref_fnotes <- mf_rfnotes(mat) |
492 | 60x |
nl_header <- mf_nlheader(mat) |
493 | ||
494 | 60x |
cell_widths_mat <- .calc_cell_widths(mat, widths, col_gap) |
495 | ||
496 |
# decimal alignment |
|
497 | 60x |
if (any_dec_align(aligns)) { |
498 | 18x |
body <- decimal_align(body, aligns) |
499 |
} |
|
500 | ||
501 |
# Content is a matrix of cells with the right amount of spaces |
|
502 | 60x |
content <- matrix(mapply(padstr, body, cell_widths_mat, aligns), ncol = ncol(body)) |
503 | 60x |
content[!keep_mat] <- NA |
504 | ||
505 |
# Define gap string and divisor string |
|
506 | 60x |
gap_str <- strrep(" ", col_gap) |
507 | 60x |
div <- substr(strrep(hsep, ncchar), 1, ncchar) |
508 | ||
509 |
# text head (paste w/o NA content header and gap string) |
|
510 | 60x |
txt_head <- apply(head(content, nl_header), 1, .paste_no_na, collapse = gap_str) |
511 | ||
512 |
# txt body |
|
513 | 60x |
sec_seps_df <- x$row_info[, c("abs_rownumber", "trailing_sep"), drop = FALSE] |
514 | 60x |
if (!is.null(sec_seps_df) && any(!is.na(sec_seps_df$trailing_sep))) { |
515 | 1x |
bdy_cont <- tail(content, -nl_header) |
516 |
## unfortunately we count "header rows" wrt line grouping so it |
|
517 |
## doesn't match the real (i.e. body) rows as is |
|
518 | 1x |
row_grouping <- tail(x$line_grouping, -nl_header) - mf_nrheader(x) |
519 | 1x |
nrbody <- NROW(bdy_cont) |
520 | 1x |
stopifnot(length(row_grouping) == nrbody) |
521 |
## all rows with non-NA section divs and the final row (regardless of NA status) |
|
522 |
## fixes #77 |
|
523 | 1x |
sec_seps_df <- sec_seps_df[unique(c( |
524 | 1x |
which(!is.na(sec_seps_df$trailing_sep)), |
525 | 1x |
NROW(sec_seps_df) |
526 |
)), ] |
|
527 | 1x |
txt_body <- character() |
528 | 1x |
sec_strt <- 1 |
529 | 1x |
section_rws <- sec_seps_df$abs_rownumber |
530 | 1x |
for (i in seq_len(NROW(section_rws))) { |
531 | 2x |
cur_rownum <- section_rws[i] |
532 | 2x |
sec_end <- max(which(row_grouping == cur_rownum)) |
533 | 2x |
txt_body <- c( |
534 | 2x |
txt_body, |
535 | 2x |
apply(bdy_cont[seq(sec_strt, sec_end), , drop = FALSE], |
536 | 2x |
1, |
537 | 2x |
.paste_no_na, |
538 | 2x |
collapse = gap_str |
539 |
), |
|
540 |
## don't print section dividers if they would be the last thing before the |
|
541 |
## footer divider |
|
542 |
## this also ensures an extraneous sec div won't be printed if we have non-sec-div |
|
543 |
## rows after the last sec div row (#77) |
|
544 | 2x |
if (sec_end < nrbody) { |
545 | 1x |
substr( |
546 | 1x |
strrep(sec_seps_df$trailing_sep[i], ncchar), 1, |
547 | 1x |
ncchar - inset |
548 |
) |
|
549 |
} |
|
550 |
) |
|
551 | 2x |
sec_strt <- sec_end + 1 |
552 |
} |
|
553 |
} else { |
|
554 |
# This is the usual default pasting |
|
555 | 59x |
txt_body <- apply(tail(content, -nl_header), 1, .paste_no_na, collapse = gap_str) |
556 |
} |
|
557 | ||
558 |
# retrieving titles and footers |
|
559 | 60x |
allts <- all_titles(x) |
560 | ||
561 |
# Fix for ref_fnotes with \n characters XXX this does not count in the pagination |
|
562 | 60x |
if (any(grepl("\n", ref_fnotes))) { |
563 | 2x |
ref_fnotes <- unlist(strsplit(ref_fnotes, "\n", fixed = TRUE)) |
564 |
} |
|
565 | ||
566 | 60x |
allfoots <- list( |
567 | 60x |
"main_footer" = main_footer(x), |
568 | 60x |
"prov_footer" = prov_footer(x), |
569 | 60x |
"ref_footnotes" = ref_fnotes |
570 |
) |
|
571 | 60x |
allfoots <- allfoots[!sapply(allfoots, is.null)] |
572 | ||
573 |
## Wrapping titles if they go beyond the horizontally allowed space |
|
574 | 60x |
if (tf_wrap) { |
575 | 16x |
new_line_warning(allts) |
576 | 16x |
allts <- wrap_txt(allts, max_width) |
577 |
} |
|
578 | 59x |
titles_txt <- if (any(nzchar(allts))) c(allts, "", .do_inset(div, inset)) else NULL |
579 | ||
580 |
# Wrapping footers if they go beyond the horizontally allowed space |
|
581 | 59x |
if (tf_wrap) { |
582 | 15x |
new_line_warning(allfoots) |
583 | 15x |
allfoots$main_footer <- wrap_txt(allfoots$main_footer, max_width - inset) |
584 | 15x |
allfoots$ref_footnotes <- wrap_txt(allfoots$ref_footnotes, max_width - inset) |
585 |
## no - inset here because the prov_footer is not inset |
|
586 | 15x |
allfoots$prov_footer <- wrap_txt(allfoots$prov_footer, max_width) |
587 |
} |
|
588 | ||
589 |
# Final return |
|
590 | 59x |
paste0( |
591 | 59x |
paste( |
592 | 59x |
c( |
593 | 59x |
titles_txt, # .do_inset(div, inset) happens if there are any titles |
594 | 59x |
.do_inset(txt_head, inset), |
595 | 59x |
.do_inset(div, inset), |
596 | 59x |
.do_inset(txt_body, inset), |
597 | 59x |
.footer_inset_helper(allfoots, div, inset) |
598 |
), |
|
599 | 59x |
collapse = "\n" |
600 | 59x |
), "\n") |
601 |
}) |
|
602 | ||
603 |
.do_inset <- function(x, inset) { |
|
604 | 322x |
if (inset == 0 || !any(nzchar(x))) { |
605 | 303x |
return(x) |
606 |
} |
|
607 | 19x |
padding <- strrep(" ", inset) |
608 | 19x |
if (is.character(x)) { |
609 | 19x |
x <- paste0(padding, x) |
610 | ! |
} else if (is(x, "matrix")) { |
611 | ! |
x[, 1] <- .do_inset(x[, 1, drop = TRUE], inset) |
612 |
} |
|
613 | 19x |
x |
614 |
} |
|
615 | ||
616 | ||
617 |
.inset_div <- function(txt, div, inset) { |
|
618 | 38x |
c(.do_inset(div, inset), "", txt) |
619 |
} |
|
620 | ||
621 |
.footer_inset_helper <- function(footers_v, div, inset) { |
|
622 | 59x |
div_done <- FALSE # nolint |
623 | 59x |
fter <- footers_v$main_footer |
624 | 59x |
prvf <- footers_v$prov_footer |
625 | 59x |
rfn <- footers_v$ref_footnotes |
626 | 59x |
footer_txt <- .do_inset(rfn, inset) |
627 | 59x |
if (any(nzchar(footer_txt))) { |
628 | 13x |
footer_txt <- .inset_div(footer_txt, div, inset) |
629 |
} |
|
630 | 59x |
if (any(vapply( |
631 | 59x |
footers_v, function(x) any(nzchar(x)), |
632 | 59x |
TRUE |
633 |
))) { |
|
634 | 25x |
if (any(nzchar(prvf))) { |
635 | 23x |
provtxt <- c( |
636 | 23x |
if (any(nzchar(fter))) "", |
637 | 23x |
prvf |
638 |
) |
|
639 |
} else { |
|
640 | 2x |
provtxt <- character() |
641 |
} |
|
642 | 25x |
footer_txt <- c( |
643 | 25x |
footer_txt, |
644 | 25x |
.inset_div( |
645 | 25x |
c( |
646 | 25x |
.do_inset(fter, inset), |
647 | 25x |
provtxt |
648 |
), |
|
649 | 25x |
div, |
650 | 25x |
inset |
651 |
) |
|
652 |
) |
|
653 |
} |
|
654 | 59x |
footer_txt |
655 |
} |
|
656 | ||
657 |
new_line_warning <- function(str_v) { |
|
658 | 31x |
if (any(unlist(sapply(str_v, grepl, pattern = "\n")))) { |
659 | 1x |
msg <- c( |
660 | 1x |
"Detected manual newlines when automatic title/footer word-wrapping is on.", |
661 | 1x |
"This is unsupported and will result in undefined behavior. Please either ", |
662 | 1x |
"utilize automatic word-wrapping with newline characters inserted, or ", |
663 | 1x |
"turn off automatic wrapping and wordwrap all contents manually by inserting ", |
664 | 1x |
"newlines." |
665 |
) |
|
666 | 1x |
warning(paste0(msg, collapse = "")) |
667 |
} |
|
668 |
} |
|
669 | ||
670 | ||
671 |
#' Wrap a string to within a precise width |
|
672 |
#' |
|
673 |
#' @description |
|
674 |
#' Core wrapping functionality that preserve white spaces. Only `"\n"` is not supported |
|
675 |
#' by core functionality [stringi::stri_wrap()]. This is usually solved before hand by |
|
676 |
#' [matrix_form()]. If the width is smaller than any large word, these will be truncated |
|
677 |
#' after `width` characters. If the split leaves trailing groups of empty spaces, |
|
678 |
#' they will be dropped. |
|
679 |
#' |
|
680 |
#' @param str character. String to be wrapped. If it is a character vector or |
|
681 |
#' a list, it will be looped as a list and returned with `unlist(use.names = FALSE)`. |
|
682 |
#' @param width numeric(1). Width, in characters, that the |
|
683 |
#' text should be wrapped at. |
|
684 |
#' @param collapse character(1) or `NULL`. If the words that have been split should |
|
685 |
#' be pasted together with the collapse character. This is usually done internally |
|
686 |
#' with `"\n"` to have the wrapping updated along with other internal values. |
|
687 |
#' |
|
688 |
#' @details Word wrapping happens as with [stringi::stri_wrap()] |
|
689 |
#' with the following exception: individual words which are longer |
|
690 |
#' than `max_width` are broken up in a way that fits with the rest of the |
|
691 |
#' word wrapping. |
|
692 |
#' |
|
693 |
#' @return A string if `str` is one element and if `collapse = NULL`. Otherwise, is |
|
694 |
#' a list of elements (if `length(str) > 1`) that can contain strings or vector of |
|
695 |
#' characters (if `collapse = NULL`). |
|
696 |
#' |
|
697 |
#' @examples |
|
698 |
#' str <- list(" , something really \\tnot very good", # \t needs to be escaped |
|
699 |
#' " but I keep it12 ") |
|
700 |
#' wrap_string(str, 5, collapse = "\n") |
|
701 |
#' |
|
702 |
#' @name wrap_string |
|
703 |
#' @export |
|
704 |
wrap_string <- function(str, width, collapse = NULL) { |
|
705 | 16268x |
if (length(str) > 1) { |
706 | 21x |
return( |
707 | 21x |
unlist( |
708 | 21x |
lapply(str, wrap_string, width = width, collapse = collapse), |
709 | 21x |
use.names = FALSE |
710 |
) |
|
711 |
) |
|
712 |
} |
|
713 | 16247x |
str <- unlist(str, use.names = FALSE) # it happens is one list element |
714 | 16247x |
if (!length(str) || !nzchar(str) || is.na(str)) { |
715 | 2404x |
return(str) |
716 |
} |
|
717 | 13843x |
checkmate::assert_character(str) |
718 | 13843x |
checkmate::assert_int(width, lower = 1) |
719 | ||
720 | 13843x |
if (any(grepl("\\n", str))) { |
721 | 1x |
stop("Found \\n in a string that was meant to be wrapped. This should not happen ", |
722 | 1x |
"because matrix_form should take care of them before this step (toString, ", |
723 | 1x |
"i.e. the printing machinery). Please contact the maintaner or file an issue.") |
724 |
} |
|
725 | ||
726 |
# str can be also a vector or list. In this case simplify manages the output |
|
727 | 13842x |
ret <- .go_stri_wrap(str, width) |
728 | ||
729 |
# Check if it went fine |
|
730 | 13842x |
if (any(nchar(ret) > width)) { |
731 | 45x |
which_exceeded <- which(nchar(ret) > width) |
732 | ||
733 |
# Recursive for loop to take word interval |
|
734 | 45x |
while (length(which_exceeded) > 0) { |
735 | 52x |
we_i <- which_exceeded[1] |
736 |
# Is there space for some part of the next word? |
|
737 | 52x |
char_threshold <- width * (2 / 3) + 0.01 # if too little space -> no previous word |
738 | 52x |
smart_condition <- nchar(ret[we_i - 1]) + 1 < char_threshold # +1 is for spaces |
739 | 52x |
if (we_i - 1 > 0 && smart_condition) { |
740 | 6x |
we_interval <- unique(c(we_i - 1, we_i)) |
741 | 6x |
we_interval <- we_interval[ |
742 | 6x |
(we_interval < (length(ret) + 1)) & |
743 | 6x |
(we_interval > 0) |
744 |
] |
|
745 |
} else { |
|
746 | 46x |
we_interval <- we_i |
747 |
} |
|
748 |
# Split words and collapse (needs unique afterwards) |
|
749 | 52x |
ret[we_interval] <- split_words_by( |
750 | 52x |
paste0(ret[we_interval], collapse = " "), |
751 | 52x |
width |
752 |
) |
|
753 |
# Taking out repetitions if there are more than one |
|
754 | 52x |
if (length(we_interval) > 1) { |
755 | 6x |
ret <- ret[-we_interval[-1]] |
756 | 6x |
we_interval <- we_interval[1] |
757 |
} |
|
758 |
# Paste together and rerun if it is not the same as original ret |
|
759 | 52x |
ret_collapse <- paste0(ret, collapse = " ") |
760 | ||
761 |
# Checking if we are stuck in a loop |
|
762 | 52x |
ori_wrapped_txt_v <- .go_stri_wrap(str, width) |
763 | 52x |
cur_wrapped_txt_v <- .go_stri_wrap(ret_collapse, width) |
764 | 52x |
if (!setequal(ori_wrapped_txt_v, cur_wrapped_txt_v)) { |
765 | 43x |
return(wrap_string(str = ret_collapse, width = width, collapse = collapse)) |
766 |
} else { |
|
767 |
# help function: Very rare case where the recursion is stuck in a loop |
|
768 | 9x |
ret_tmp <- force_split_words_by(ret[we_interval], width) # here we_interval is only one ind |
769 | 9x |
ret <- append(ret, ret_tmp, we_interval)[-we_interval] |
770 | 9x |
which_exceeded <- which(nchar(ret) > width) |
771 |
} |
|
772 |
} |
|
773 |
} |
|
774 | ||
775 | 13799x |
if (!is.null(collapse)) { |
776 | 13669x |
return(paste0(ret, collapse = collapse)) |
777 |
} |
|
778 | ||
779 | 130x |
return(ret) |
780 |
} |
|
781 | ||
782 |
.go_stri_wrap <- function(str, w) { |
|
783 | 13946x |
stringi::stri_wrap(str, |
784 | 13946x |
width = w, |
785 | 13946x |
normalize = FALSE, # keeps spaces |
786 | 13946x |
simplify = TRUE, # If FALSE makes it a list with str elements |
787 | 13946x |
indent = 0 |
788 |
) |
|
789 |
} |
|
790 | ||
791 |
# help function: Very rare case where the recursion is stuck in a loop |
|
792 |
force_split_words_by <- function(ret, width) { |
|
793 | 9x |
which_exceeded <- which(nchar(ret) > width) |
794 | 9x |
ret_tmp <- NULL |
795 | 9x |
for (ii in seq_along(ret)) { |
796 | 9x |
if (ii %in% which_exceeded) { |
797 | 9x |
wrd_i <- ret[ii] |
798 | 9x |
init_v <- seq(1, nchar(wrd_i), by = width) |
799 | 9x |
end_v <- c(init_v[-1] - 1, nchar(wrd_i)) |
800 | 9x |
str_v_tmp <- stringi::stri_sub(wrd_i, from = init_v, to = end_v) |
801 | 9x |
ret_tmp <- c(ret_tmp, str_v_tmp[!grepl("^\\s+$", str_v_tmp) & nzchar(str_v_tmp)]) |
802 |
} else { |
|
803 | ! |
ret_tmp <- c(ret_tmp, ret[ii]) |
804 |
} |
|
805 |
} |
|
806 | 9x |
ret_tmp |
807 |
} |
|
808 | ||
809 |
# Helper fnc to split the words and collapse them with space |
|
810 |
split_words_by <- function(wrd, width) { |
|
811 | 52x |
vapply(wrd, function(wrd_i) { |
812 | 52x |
init_v <- seq(1, nchar(wrd_i), by = width) |
813 | 52x |
end_v <- c(init_v[-1] - 1, nchar(wrd_i)) |
814 | 52x |
fin_str_v <- substring(wrd_i, init_v, end_v) |
815 | 52x |
is_only_spaces <- grepl("^\\s+$", fin_str_v) |
816 |
# We pop only spaces at this point |
|
817 | 52x |
if (all(is_only_spaces)) { |
818 | ! |
fin_str_v <- fin_str_v[1] # keep only one width-sized empty |
819 |
} else { |
|
820 | 52x |
fin_str_v <- fin_str_v[!is_only_spaces] # hybrid text + \s |
821 |
} |
|
822 | ||
823 |
# Collapse the string |
|
824 | 52x |
paste0(fin_str_v, collapse = " ") |
825 | 52x |
}, character(1), USE.NAMES = FALSE) |
826 |
} |
|
827 | ||
828 |
#' @describeIn wrap_string function that flattens the list of wrapped strings with |
|
829 |
#' `unist(str, use.names = FALSE)`. This is deprecated, use [wrap_string()] instead. |
|
830 |
#' @examples |
|
831 |
#' wrap_txt(str, 5, collapse = NULL) |
|
832 |
#' |
|
833 |
#' @export |
|
834 |
wrap_txt <- function(str, width, collapse = NULL) { |
|
835 | 112x |
unlist(wrap_string(str, width, collapse), use.names = FALSE) |
836 |
} |
|
837 | ||
838 |
pad_vert_top <- function(x, len, default = "") { |
|
839 | 4952x |
c(x, rep(default, len - length(x))) |
840 |
} |
|
841 | ||
842 |
pad_vert_bottom <- function(x, len, default = "") { |
|
843 | 192x |
c(rep(default, len - length(x)), x) |
844 |
} |
|
845 | ||
846 |
pad_vec_to_len <- function(vec, len, cpadder = pad_vert_top, rlpadder = cpadder) { |
|
847 | 463x |
dat <- unlist(lapply(vec[-1], cpadder, len = len)) |
848 | 463x |
dat <- c(rlpadder(vec[[1]], len = len), dat) |
849 | 463x |
matrix(dat, nrow = len) |
850 |
} |
|
851 | ||
852 |
rep_vec_to_len <- function(vec, len, ...) { |
|
853 | 448x |
matrix(unlist(lapply(vec, rep, times = len)), |
854 | 448x |
nrow = len |
855 |
) |
|
856 |
} |
|
857 | ||
858 | ||
859 |
safe_strsplit <- function(x, split, ...) { |
|
860 | 687x |
ret <- strsplit(x, split, ...) |
861 | 687x |
lapply(ret, function(reti) if (length(reti) == 0) "" else reti) |
862 |
} |
|
863 | ||
864 |
.expand_mat_rows_inner <- function(i, mat, row_nlines, expfun, ...) { |
|
865 | 911x |
leni <- row_nlines[i] |
866 | 911x |
rw <- mat[i, ] |
867 | 911x |
if (is.character(rw)) { |
868 | 687x |
rw <- safe_strsplit(rw, "\n", fixed = TRUE) |
869 |
} |
|
870 | 911x |
expfun(rw, len = leni, ...) |
871 |
} |
|
872 | ||
873 |
expand_mat_rows <- function(mat, row_nlines = apply(mat, 1, nlines), expfun = pad_vec_to_len, ...) { |
|
874 | 84x |
rinds <- seq_len(nrow(mat)) |
875 | 84x |
exprows <- lapply(rinds, .expand_mat_rows_inner, |
876 | 84x |
mat = mat, |
877 | 84x |
row_nlines = row_nlines, |
878 | 84x |
expfun = expfun, |
879 |
... |
|
880 |
) |
|
881 | 84x |
do.call(rbind, exprows) |
882 |
} |
|
883 | ||
884 | ||
885 |
#' Transform vectors of spans (with duplication) to Visibility vector |
|
886 |
#' |
|
887 |
#' @param spans numeric. A vector of spans, with each span value repeated |
|
888 |
#' for the cells it covers. |
|
889 |
#' |
|
890 |
#' @details |
|
891 |
#' |
|
892 |
#' The values of \code{spans} are assumed to be repeated to such that |
|
893 |
#' each individual position covered by the span has the repeated value. |
|
894 |
#' |
|
895 |
#' This means that each block of values in \code{span} must be of a length |
|
896 |
#' at least equal to its value (i.e. two 2s, three 3s, etc). |
|
897 |
#' |
|
898 |
#' This function correctly handles cases where two spans of the same size |
|
899 |
#' are next to each other; i.e., a block of four 2s represents two large |
|
900 |
#' cells each of which span two individual cells. |
|
901 |
#' @export |
|
902 |
#' @note |
|
903 |
#' |
|
904 |
#' Currently no checking or enforcement is done that the vector of |
|
905 |
#' spans is valid in the sense described in the Details section above. |
|
906 |
#' @examples |
|
907 |
#' |
|
908 |
#' spans_to_viscell(c(2, 2, 2, 2, 1, 3, 3, 3)) |
|
909 |
#' @return a logical vector the same length as `spans` indicating |
|
910 |
#' whether the contents of a string vector with those spans |
|
911 |
spans_to_viscell <- function(spans) { |
|
912 | 2x |
if (!is.vector(spans)) { |
913 | ! |
spans <- as.vector(spans) |
914 |
} |
|
915 | 2x |
myrle <- rle(spans) |
916 | 2x |
unlist( |
917 | 2x |
mapply( |
918 | 2x |
function(vl, ln) { |
919 | 4x |
rep(c(TRUE, rep(FALSE, vl - 1L)), times = ln / vl) |
920 |
}, |
|
921 | 2x |
SIMPLIFY = FALSE, |
922 | 2x |
vl = myrle$values, |
923 | 2x |
ln = myrle$lengths |
924 |
), |
|
925 | 2x |
recursive = FALSE |
926 |
) |
|
927 |
} |
|
928 | ||
929 | ||
930 |
#' Propose Column Widths based on an object's `MatrixPrintForm` form |
|
931 |
#' |
|
932 |
#' The row names are also considered a column for the output |
|
933 |
#' |
|
934 |
#' @param x `MatrixPrintForm` object, or an object with a `matrix_form` |
|
935 |
#' method. |
|
936 |
#' @param indent_size numeric(1). Indent size in characters. Ignored |
|
937 |
#' when `x` is already a `MatrixPrintForm` object in favor of information |
|
938 |
#' there. |
|
939 |
#' |
|
940 |
#' @examples |
|
941 |
#' mf <- basic_matrix_form(mtcars) |
|
942 |
#' propose_column_widths(mf) |
|
943 |
#' |
|
944 |
#' @export |
|
945 |
#' @return a vector of column widths based on the content of \code{x} |
|
946 |
#' for use in printing and pagination. |
|
947 |
## ' @examples |
|
948 |
## ' library(dplyr) |
|
949 |
## ' library(rtables) |
|
950 |
## ' iris2 <- iris %>% |
|
951 |
## ' group_by(Species) %>% |
|
952 |
## ' mutate(group = as.factor(rep_len(c("a", "b"), length.out = n()))) %>% |
|
953 |
## ' ungroup() |
|
954 |
## ' |
|
955 |
## ' l <- basic_table() %>% |
|
956 |
## ' split_cols_by("Species") %>% |
|
957 |
## ' split_cols_by("group") %>% |
|
958 |
## ' analyze(c("Sepal.Length", "Petal.Width"), afun = list_wrap_x(summary) , format = "xx.xx") |
|
959 |
## ' |
|
960 |
## ' tbl <- build_table(l, iris2) |
|
961 |
## ' mf <- matrix_form(tbl) |
|
962 |
## ' propose_column_widths(mf) |
|
963 |
propose_column_widths <- function(x, indent_size = 2) { |
|
964 |
## stopifnot(is(x, "VTableTree")) |
|
965 | 69x |
if (!is(x, "MatrixPrintForm")) { |
966 | ! |
x <- matrix_form(x, indent_rownames = TRUE, indent_size = indent_size) |
967 |
} |
|
968 | 69x |
body <- mf_strings(x) |
969 | 69x |
spans <- mf_spans(x) |
970 | 69x |
aligns <- mf_aligns(x) |
971 | 69x |
display <- mf_display(x) |
972 | ||
973 |
# compute decimal alignment if asked in alignment matrix |
|
974 | 69x |
if (any_dec_align(aligns)) { |
975 | 27x |
body <- decimal_align(body, aligns) |
976 |
} |
|
977 | ||
978 | 66x |
chars <- nchar(body) |
979 | ||
980 |
# first check column widths without colspan |
|
981 | 66x |
has_spans <- spans != 1 |
982 | 66x |
chars_ns <- chars |
983 | 66x |
chars_ns[has_spans] <- 0 |
984 | 66x |
widths <- apply(chars_ns, 2, max) |
985 | ||
986 |
# now check if the colspans require extra width |
|
987 | 66x |
if (any(has_spans)) { |
988 | 1x |
has_row_spans <- apply(has_spans, 1, any) |
989 | ||
990 | 1x |
chars_sp <- chars[has_row_spans, , drop = FALSE] |
991 | 1x |
spans_sp <- spans[has_row_spans, , drop = FALSE] |
992 | 1x |
disp_sp <- display[has_row_spans, , drop = FALSE] |
993 | ||
994 | 1x |
nc <- ncol(spans) |
995 | 1x |
for (i in seq_len(nrow(chars_sp))) { |
996 | 1x |
for (j in seq_len(nc)) { |
997 | 2x |
if (disp_sp[i, j] && spans_sp[i, j] != 1) { |
998 | 1x |
i_cols <- seq(j, j + spans_sp[i, j] - 1) |
999 | ||
1000 | 1x |
nchar_i <- chars_sp[i, j] |
1001 | 1x |
cw_i <- widths[i_cols] |
1002 | 1x |
available_width <- sum(cw_i) |
1003 | ||
1004 | 1x |
if (nchar_i > available_width) { |
1005 |
# need to update widths to fit content with colspans |
|
1006 |
# spread width among columns |
|
1007 | ! |
widths[i_cols] <- cw_i + spread_integer(nchar_i - available_width, length(cw_i)) |
1008 |
} |
|
1009 |
} |
|
1010 |
} |
|
1011 |
} |
|
1012 |
} |
|
1013 | 66x |
widths |
1014 |
} |
|
1015 | ||
1016 | ||
1017 | ||
1018 | ||
1019 |
#' Pad a string and align within string |
|
1020 |
#' |
|
1021 |
#' @param x string |
|
1022 |
#' @param n number of character of the output string, if `n < |
|
1023 |
#' nchar(x)` an error is thrown |
|
1024 |
#' @param just character(1). Text alignment justification to |
|
1025 |
#' use. Defaults to `center`. Must be `center`, `right`, `left`, |
|
1026 |
#' `dec_right`, `dec_left` or `decimal`. |
|
1027 |
#' |
|
1028 |
#' @export |
|
1029 |
#' @examples |
|
1030 |
#' |
|
1031 |
#' padstr("abc", 3) |
|
1032 |
#' padstr("abc", 4) |
|
1033 |
#' padstr("abc", 5) |
|
1034 |
#' padstr("abc", 5, "left") |
|
1035 |
#' padstr("abc", 5, "right") |
|
1036 |
#' |
|
1037 |
#' if (interactive()) { |
|
1038 |
#' padstr("abc", 1) |
|
1039 |
#' } |
|
1040 |
#' @return `x`, padded to be a string of `n` characters |
|
1041 |
#' |
|
1042 |
padstr <- function(x, n, just = list_valid_aligns()) { |
|
1043 | 5087x |
just <- match.arg(just) |
1044 | ||
1045 | 1x |
if (length(x) != 1) stop("length of x needs to be 1 and not", length(x)) |
1046 | 1x |
if (is.na(n) || !is.numeric(n) || n < 0) stop("n needs to be numeric and > 0") |
1047 | ||
1048 | 2x |
if (is.na(x)) x <- "<NA>" |
1049 | ||
1050 | 5085x |
nc <- nchar(x) |
1051 | ||
1052 | ! |
if (n < nc) stop("\"", x, "\" has more than ", n, " characters") |
1053 | ||
1054 | 5085x |
switch(just, |
1055 |
center = { |
|
1056 | 275x |
pad <- (n - nc) / 2 |
1057 | 275x |
paste0(spaces(floor(pad)), x, spaces(ceiling(pad))) |
1058 |
}, |
|
1059 | 4661x |
left = paste0(x, spaces(n - nc)), |
1060 | 10x |
right = paste0(spaces(n - nc), x), |
1061 |
decimal = { |
|
1062 | 60x |
pad <- (n - nc) / 2 |
1063 | 60x |
paste0(spaces(floor(pad)), x, spaces(ceiling(pad))) |
1064 |
}, |
|
1065 | 44x |
dec_left = paste0(x, spaces(n - nc)), |
1066 | 35x |
dec_right = paste0(spaces(n - nc), x) |
1067 |
) |
|
1068 |
} |
|
1069 | ||
1070 |
spaces <- function(n) { |
|
1071 | 5578x |
strrep(" ", n) |
1072 |
} |
|
1073 | ||
1074 | ||
1075 |
.paste_no_na <- function(x, ...) { |
|
1076 | 894x |
paste(na.omit(x), ...) |
1077 |
} |
|
1078 | ||
1079 | ||
1080 |
#' spread `x` into `len` elements |
|
1081 |
#' |
|
1082 |
#' @param x numeric(1). The number to spread |
|
1083 |
#' @param len numeric(1). The number of times to repeat \code{x} |
|
1084 |
#' |
|
1085 |
#' @export |
|
1086 |
#' @return if \code{x} is a scalar "whole number" value (see \code{\link{is.wholenumber}}), |
|
1087 |
#' the value \code{x} repeated \code{len} times. If not, an error is thrown. |
|
1088 |
#' @examples |
|
1089 |
#' spread_integer(3, 1) |
|
1090 |
#' spread_integer(0, 3) |
|
1091 |
#' spread_integer(1, 3) |
|
1092 |
#' spread_integer(2, 3) |
|
1093 |
#' spread_integer(3, 3) |
|
1094 |
#' spread_integer(4, 3) |
|
1095 |
#' spread_integer(5, 3) |
|
1096 |
#' spread_integer(6, 3) |
|
1097 |
#' spread_integer(7, 3) |
|
1098 |
spread_integer <- function(x, len) { |
|
1099 | 2x |
stopifnot( |
1100 | 2x |
is.wholenumber(x), length(x) == 1, x >= 0, |
1101 | 2x |
is.wholenumber(len), length(len) == 1, len >= 0, |
1102 | 2x |
!(len == 0 && x > 0) |
1103 |
) |
|
1104 | ||
1105 | ||
1106 | 1x |
if (len == 0) { |
1107 | ! |
integer(0) |
1108 |
} else { |
|
1109 | 1x |
y <- rep(floor(x / len), len) |
1110 | 1x |
i <- 1 |
1111 | 1x |
while (sum(y) < x) { |
1112 | 1x |
y[i] <- y[i] + 1 |
1113 | 1x |
if (i == len) { |
1114 | ! |
i <- 1 |
1115 |
} else { |
|
1116 | 1x |
i <- i + 1 |
1117 |
} |
|
1118 |
} |
|
1119 | 1x |
y |
1120 |
} |
|
1121 |
} |
|
1122 | ||
1123 | ||
1124 | ||
1125 |
#' `is.wholenumber` |
|
1126 |
#' |
|
1127 |
#' @param x numeric(1). A numeric value |
|
1128 |
#' @param tol numeric(1). A precision tolerance. |
|
1129 |
#' |
|
1130 |
#' @return \code{TRUE} if \code{x} is within \code{tol} of zero, |
|
1131 |
#' \code{FALSE} otherwise. |
|
1132 |
#' |
|
1133 |
#' @export |
|
1134 |
#' @examples |
|
1135 |
#' is.wholenumber(5) |
|
1136 |
#' is.wholenumber(5.00000000000000001) |
|
1137 |
#' is.wholenumber(.5) |
|
1138 |
#' |
|
1139 |
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) { |
|
1140 | 3x |
abs(x - round(x)) < tol |
1141 |
} |
1 | ||
2 | ||
3 | ||
4 | ||
5 |
#' Return an object with a label attribute |
|
6 |
#' |
|
7 |
#' @param x an object |
|
8 |
#' @param label label attribute to to attached to \code{x} |
|
9 |
#' |
|
10 |
#' @export |
|
11 |
#' @return \code{x} labeled by \code{label}. Note: the exact mechanism of labeling should be |
|
12 |
#' considered an internal implementation detail, but the label will always be retrieved via \code{obj_label}. |
|
13 |
#' @examples |
|
14 |
#' x <- with_label(c(1, 2, 3), label = "Test") |
|
15 |
#' obj_label(x) |
|
16 |
with_label <- function(x, label) { |
|
17 | 1x |
obj_label(x) <- label |
18 | 1x |
x |
19 |
} |
|
20 | ||
21 | ||
22 |
#' Get Label Attributes of Variables in a \code{data.frame} |
|
23 |
#' |
|
24 |
#' Variable labels can be stored as a \code{label} attribute for each variable. |
|
25 |
#' This functions returns a named character vector with the variable labels |
|
26 |
#' (empty sting if not specified) |
|
27 |
#' |
|
28 |
#' @param x a \code{data.frame} object |
|
29 |
#' @param fill boolean in case the \code{label} attribute does not exist if |
|
30 |
#' \code{TRUE} the variable names is returned, otherwise \code{NA} |
|
31 |
#' |
|
32 |
#' @return a named character vector with the variable labels, the names |
|
33 |
#' correspond to the variable names |
|
34 |
#' |
|
35 |
#' @export |
|
36 |
#' |
|
37 |
#' @examples |
|
38 |
#' x <- iris |
|
39 |
#' var_labels(x) |
|
40 |
#' var_labels(x) <- paste("label for", names(iris)) |
|
41 |
#' var_labels(x) |
|
42 |
var_labels <- function(x, fill = FALSE) { |
|
43 | 4x |
stopifnot(is.data.frame(x)) |
44 | 4x |
if (NCOL(x) == 0) { |
45 | 1x |
return(character()) |
46 |
} |
|
47 | ||
48 | 3x |
y <- Map(function(col, colname) { |
49 | 33x |
label <- attr(col, "label") |
50 | ||
51 | 33x |
if (is.null(label)) { |
52 | 11x |
if (fill) { |
53 | ! |
colname |
54 |
} else { |
|
55 | 3x |
NA_character_ |
56 |
} |
|
57 |
} else { |
|
58 | 22x |
if (!is.character(label) && !(length(label) == 1)) { |
59 | ! |
stop("label for variable ", colname, "is not a character string") |
60 |
} |
|
61 | 22x |
as.vector(label) |
62 |
} |
|
63 | 3x |
}, x, colnames(x)) |
64 | ||
65 | 3x |
labels <- unlist(y, recursive = FALSE, use.names = TRUE) |
66 | ||
67 | 3x |
if (!is.character(labels)) { |
68 | ! |
stop("label extraction failed") |
69 |
} |
|
70 | ||
71 | 3x |
labels |
72 |
} |
|
73 | ||
74 | ||
75 |
#' Set Label Attributes of All Variables in a \code{data.frame} |
|
76 |
#' |
|
77 |
#' Variable labels can be stored as a \code{label} attribute for each variable. |
|
78 |
#' This functions sets all non-missing (non-NA) variable labels in a \code{data.frame} |
|
79 |
#' |
|
80 |
#' @inheritParams var_labels |
|
81 |
#' @param value new variable labels, \code{NA} removes the variable label |
|
82 |
#' |
|
83 |
#' @return modifies the variable labels of \code{x} |
|
84 |
#' |
|
85 |
#' @export |
|
86 |
#' |
|
87 |
#' @examples |
|
88 |
#' x <- iris |
|
89 |
#' var_labels(x) |
|
90 |
#' var_labels(x) <- paste("label for", names(iris)) |
|
91 |
#' var_labels(x) |
|
92 |
#' |
|
93 |
#' if (interactive()) { |
|
94 |
#' View(x) # in RStudio data viewer labels are displayed |
|
95 |
#' } |
|
96 |
`var_labels<-` <- function(x, value) { |
|
97 | 1x |
stopifnot( |
98 | 1x |
is.data.frame(x), |
99 | 1x |
is.character(value), |
100 | 1x |
ncol(x) == length(value) |
101 |
) |
|
102 | ||
103 | 1x |
theseq <- if (!is.null(names(value))) names(value) else seq_along(x) |
104 |
# across columns of x |
|
105 | 1x |
for (j in theseq) { |
106 | 11x |
attr(x[[j]], "label") <- if (!is.na(value[j])) { |
107 | 11x |
value[j] |
108 |
} else { |
|
109 | ! |
NULL |
110 |
} |
|
111 |
} |
|
112 | ||
113 | 1x |
x |
114 |
} |
|
115 | ||
116 | ||
117 |
#' Copy and Change Variable Labels of a \code{data.frame} |
|
118 |
#' |
|
119 |
#' Relabel a subset of the variables |
|
120 |
#' |
|
121 |
#' @inheritParams var_labels<- |
|
122 |
#' @param ... name-value pairs, where name corresponds to a variable name in |
|
123 |
#' \code{x} and the value to the new variable label |
|
124 |
#' |
|
125 |
#' @return a copy of \code{x} with changed labels according to \code{...} |
|
126 |
#' |
|
127 |
#' @export |
|
128 |
#' |
|
129 |
#' @examples |
|
130 |
#' x <- var_relabel(iris, Sepal.Length = "Sepal Length of iris flower") |
|
131 |
#' var_labels(x) |
|
132 |
#' |
|
133 |
var_relabel <- function(x, ...) { |
|
134 |
# todo: make this function more readable / code easier |
|
135 | 1x |
stopifnot(is.data.frame(x)) |
136 | 1x |
if (missing(...)) { |
137 | ! |
return(x) |
138 |
} |
|
139 | 1x |
dots <- list(...) |
140 | 1x |
varnames <- names(dots) |
141 | 1x |
stopifnot(!is.null(varnames)) |
142 | ||
143 | 1x |
map_varnames <- match(varnames, colnames(x)) |
144 | ||
145 | 1x |
if (any(is.na(map_varnames))) { |
146 | ! |
stop("variables: ", paste(varnames[is.na(map_varnames)], collapse = ", "), " not found") |
147 |
} |
|
148 | ||
149 | 1x |
if (any(vapply(dots, Negate(is.character), logical(1)))) { |
150 | ! |
stop("all variable labels must be of type character") |
151 |
} |
|
152 | ||
153 | 1x |
for (i in seq_along(map_varnames)) { |
154 | 1x |
attr(x[[map_varnames[[i]]]], "label") <- dots[[i]] |
155 |
} |
|
156 | ||
157 | 1x |
x |
158 |
} |
|
159 | ||
160 | ||
161 |
#' Remove Variable Labels of a \code{data.frame} |
|
162 |
#' |
|
163 |
#' Removing labels attributes from a variables in a data frame |
|
164 |
#' |
|
165 |
#' @param x a \code{data.frame} object |
|
166 |
#' |
|
167 |
#' @return the same data frame as \code{x} stripped of variable labels |
|
168 |
#' |
|
169 |
#' @export |
|
170 |
#' |
|
171 |
#' @examples |
|
172 |
#' x <- var_labels_remove(iris) |
|
173 |
var_labels_remove <- function(x) { |
|
174 | 1x |
stopifnot(is.data.frame(x)) |
175 | ||
176 | 1x |
for (i in seq_len(ncol(x))) { |
177 | 11x |
attr(x[[i]], "label") <- NULL |
178 |
} |
|
179 | ||
180 | 1x |
x |
181 |
} |
1 |
## credit: rlang, Henry and Wickham. |
|
2 |
## this one tiny utility function is NOT worth a dependency. |
|
3 |
## modified it so any length 0 x grabs y |
|
4 | ||
5 |
#' `%||%` If length-0 alternative operator |
|
6 |
#' @name ifnotlen0 |
|
7 |
#' |
|
8 |
#' @param a ANY. Element to select only if it is not length 0 |
|
9 |
#' @param b ANY. Element to select if \code{a} is length 0 |
|
10 |
#' @export |
|
11 |
#' @examples |
|
12 |
#' 6 %||% 10 |
|
13 |
#' |
|
14 |
#' character() %||% "hi" |
|
15 |
#' |
|
16 |
#' NULL %||% "hi" |
|
17 |
#' @return `a`, unless it is length 0, in which case `b` (even in the |
|
18 |
#' case `b` is also length 0) |
|
19 |
`%||%` <- function(a, b) { |
|
20 | 220x |
if (length(a) == 0) { |
21 | 32x |
b |
22 |
} else { |
|
23 | 188x |
a |
24 |
} |
|
25 |
} |