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