Debian Codegraph @

R/helpers.R

raw
1 #' Add trailing and leading blank line
2 #'
3 #' Adds a line break before \emph{and} after the character string(s).
4 #' @param x character vector
5 #' @export
6 add.blank.lines <- function(x)
7 sprintf('\n%s\n', x)
8
9
10 #' Remove more then two joined newlines
11 #' @param x character vector
12 #' @export
13 #' @examples
14 #' remove.extra.newlines(c('\n\n\n', '\n\n', '\n'))
15 remove.extra.newlines <- function(x)
16 gsub('[\n][\n]+', '\n\n', x)
17
18
19 #' Trim leading and trailing spaces
20 #' @param x character vector
21 #' @return character vector
22 #' @export
23 #' @seealso \code{trim.space} in \code{rapport} package
24 trim.spaces <- function(x)
25 gsub('^[[:space:]]+|[[:space:]]+$', '', x)
26
27 #' Repeating chars
28 #'
29 #' Repeating a string \code{n} times and returning a concatenated character vector.
30 #' @param x string to repeat
31 #' @param n integer
32 #' @param sep separator between repetitions
33 #' @return character vector
34 #' @export
35 repChar <- function(x, n, sep = '')
36 paste(rep.int(x, n), collapse = sep)
37
38
39 #' Inline Printing
40 #'
41 #' \code{\link{p}} merges elements of a vector in one string for the sake of pretty inline printing. Default parameters are read from appropriate \code{option} values (see argument description for details). This function allows you to put the results of an expression that yields a variable \emph{inline}, by wrapping the vector elements with the string provided in \code{wrap}, and separating elements by main and ending separator (\code{sep} and \code{copula}). In case of a two-length vector, value specified in \code{copula} will be used as a separator. You can also control the length of provided vector by altering an integer value specified in \code{limit} argument (defaults to \code{Inf}).
42 #' @param x an atomic vector to get merged for inline printing
43 #' @param wrap a string to wrap vector elements (uses value set in \code{p.wrap} option: \code{'_'} by default, which is a markdown-friendly wrapper and it puts the string in \emph{italic})
44 #' @param sep a string with the main separator, i.e. the one that separates all vector elements but the last two (uses the value set in \code{p.sep} option - \code{','} by default)
45 #' @param copula a string with ending separator - the one that separates the last two vector elements (uses the value set in \code{p.copula} option, \code{'and'} by default)
46 #' @param limit maximum character length (defaults to \code{Inf}initive elements)
47 #' @param keep.trailing.zeros to show or remove trailing zeros in numbers
48 #' @param missing string to replace missing values
49 #' @param digits numeric (default: 2) passed to format
50 #' @param round numeric (default: Inf) passed to round
51 #' @return a string with concatenated vector contents
52 #' @examples
53 #' p(c('fee', 'fi', 'foo', 'fam'))
54 #' # [1] '_fee_, _fi_, _foo_ and _fam_'
55 #' p(1:3, wrap = '')
56 #' # [1] '1, 2 and 3'
57 #' p(LETTERS[1:5], copula = 'and the letter')
58 #' # [1] '_A_, _B_, _C_, _D_ and the letter _E_'
59 #' p(c('Thelma', 'Louise'), wrap = '', copula = '&')
60 #' # [1] 'Thelma & Louise'
61 #' @export
62 #' @author Aleksandar Blagotic
63 #' @references This function was moved from \code{rapport} package: \url{https://rapporter.github.io/rapport/}.
64 p <- function(x, wrap = panderOptions('p.wrap'), sep = panderOptions('p.sep'), copula = panderOptions('p.copula'), limit = Inf, keep.trailing.zeros = panderOptions('keep.trailing.zeros'), missing = panderOptions('missing'), digits = panderOptions('digits'), round = panderOptions('round')){ #nolint
65
66 attributes(x) <- NULL
67 stopifnot(is.vector(x))
68 stopifnot(all(sapply(list(wrap, sep, copula), function(x) is.character(x) && length(x) == 1)))
69 x.len <- length(x)
70 if (x.len == 0) {
71 return('')
72 }
73 stopifnot(x.len <= limit)
74
75 ## store missing values
76 w <- which(is.na(x))
77
78 ## prettify numbers
79 if (is.numeric(x)) {
80
81 x <- round(x, digits = round)
82
83 ## optionally remove trailing zeros by running format separately on each element of the vector
84 if (!keep.trailing.zeros) {
85 x <- sapply(x, format, trim = TRUE, digits = digits, decimal.mark = panderOptions('decimal.mark')) #nolint
86 } else {
87 ## otherwise force using the same number format for all vector elements
88 x <- format(x, trim = TRUE, digits = digits, decimal.mark = panderOptions('decimal.mark'))
89 }
90
91 }
92
93 ## replace missing values
94 if (length(w) > 0) {
95 x[w] <- missing
96 }
97
98 if (x.len == 1) {
99 wrap(x, wrap)
100 } else if (x.len == 2) {
101 paste(wrap(x, wrap), collapse = copula)
102 } else {
103 paste0(paste(wrap(head(x, -1), wrap), collapse = sep), copula, wrap(tail(x, 1), wrap))
104 }
105 }
106
107
108 #' Wrap Vector Elements
109 #'
110 #' Wraps vector elements with string provided in \code{wrap} argument.
111 #' @param x a vector to wrap
112 #' @param wrap a string to wrap around vector elements
113 #' @return a string with wrapped elements
114 #' @examples \dontrun{
115 #' wrap('foobar')
116 #' wrap(c('fee', 'fi', 'foo', 'fam'), '_')
117 #' }
118 #' @export
119 #' @author Aleksandar Blagotic
120 #' @references This function was moved from \code{rapport} package: \url{https://rapporter.github.io/rapport/}.
121 wrap <- function(x, wrap = '"'){
122 attributes(x) <- NULL
123 stopifnot(is.vector(x))
124 sprintf('%s%s%s', wrap, x, wrap)
125 }
126
127 #' Check if rownames are available
128 #'
129 #' Dummy helper to check if the R object has real rownames or not.
130 #' @param x a tabular-like R object
131 #' @return \code{TRUE} OR \code{FALSE}
132 #' @export
133 has.rownames <- function(x) {
134 length(dim(x)) != 1 && length(rownames(x)) > 0 && !all(rownames(x) == 1:nrow(x)) && !all(rownames(x) == '')
135 }
136
137 #' Adds caption in current block
138 #'
139 #' This is a helper function to add a caption to the returning image/table.
140 #' @param x string
141 #' @param permanent (default \code{FALSE}) if caption is permanent (for all future tables) or not
142 #' @export
143 set.caption <- function(x, permanent = FALSE){
144 assign('caption', x, envir = storage)
145 if (!is.null(x)) {
146 attr(storage$caption, 'permanent') <- permanent
147 }
148 }
149
150
151 #' Get caption
152 #'
153 #' Get caption from temporary environment and truncates that
154 #' @return stored caption as string
155 #' @keywords internal
156 get.caption <- function()
157 get.storage('caption')
158
159
160 #' Sets alignment for tables
161 #'
162 #' This is a helper function to update the alignment (\code{justify} parameter in \code{pandoc.table}) of the next returning table. Possible values are: \code{centre} or \code{center}, \code{right}, \code{left}.
163 #' @param default character vector which length equals to one (would be repeated \code{n} times) ot \code{n} - where \code{n} equals to the number of columns in the following table
164 #' @param row.names string holding the alignment of the (optional) row names
165 #' @param permanent (default \code{FALSE}) if alignment is permanent (for all future tables) or not. It's cleaner to use \code{panderOptions} instead.
166 #' @export
167 set.alignment <- function(default = panderOptions('table.alignment.default'), row.names = panderOptions('table.alignment.rownames'), permanent = FALSE) { #nolint
168 assign('alignment', list(default = default, row.names = row.names), envir = storage)
169 attr(storage$alignment, 'permanent') <- permanent
170 }
171
172
173 #' Get alignment
174 #'
175 #' Get alignment from temporary environment, truncating that and applying rownames and other columns alignment to passed \code{df}.
176 #' @return vector of alignment parameters
177 #' @keywords internal
178 #' @param df data.frame
179 #' @param remove.obious.rownames if this rule should be applied or not
180 get.alignment <- function(df, remove.obious.rownames = TRUE) {
181
182 if (is.null(attr(df, 'alignment'))) {
183
184 a <- get.storage('alignment')
185
186 if (is.null(a)) {
187 ad <- panderOptions('table.alignment.default')
188 ar <- panderOptions('table.alignment.rownames')
189 if (remove.obious.rownames && !has.rownames(df)) {
190 ar <- NULL
191 }
192 if (is.function(ar)) {
193 ar <- ar()
194 }
195 if (is.function(ad)) {
196 return(c(ar, ad(df)))
197 }
198 a <- list(default = ad, row.names = ar)
199 }
200
201 if (length(a) == 1) {
202 a <- list(default = as.character(a), row.names = as.character(a))
203 }
204
205 if (length(dim(df)) < 2) {
206 w <- length(df)
207 n <- NULL
208 } else {
209 w <- ncol(df)
210 n <- rownames(df)
211 if (isTRUE(remove.obious.rownames) && all(n == 1:nrow(df))) {
212 n <- NULL
213 }
214 }
215
216 if (is.null(n)) {
217 return(rep(a$default, length.out = w))
218 } else {
219 return(c(a$row.names, rep(a$default, length.out = w)))
220 }
221
222 }
223
224 attr(df, 'alignment')
225 }
226
227
228 #' Emphasize rows/columns/cells
229 #'
230 #' Storing indexes of cells to be (strong) emphasized of a tabular data in an internal buffer that can be released and applied by \code{\link{pandoc.table}}, \code{\link{pander}} or \code{\link{evals}} later.
231 #' @param x vector of row/columns indexes or an array like returned by \code{which(..., arr.ind = TRUE)}
232 #' @aliases emphasize.rows emphasize.cols emphasize.cells emphasize.strong.rows emphasize.strong.cols emphasize.strong.cells emphasize.italics.rows emphasize.italics.cols emphasize.italics.cells emphasize.verbatim.rows emphasize.verbatim.cols emphasize.verbatim.cells
233 #' @usage
234 #' emphasize.rows(x)
235 #'
236 #' emphasize.cols(x)
237 #'
238 #' emphasize.cells(x)
239 #'
240 #' emphasize.strong.rows(x)
241 #'
242 #' emphasize.strong.cols(x)
243 #'
244 #' emphasize.strong.cells(x)
245 #'
246 #' emphasize.italics.rows(x)
247 #'
248 #' emphasize.italics.cols(x)
249 #'
250 #' emphasize.italics.cells(x)
251 #'
252 #' emphasize.verbatim.rows(x)
253 #'
254 #' emphasize.verbatim.cols(x)
255 #'
256 #' emphasize.verbatim.cells(x)
257 #' @export
258 #' @examples \dontrun{
259 #' n <- data.frame(x = c(1,1,1,1,1), y = c(0,1,0,1,0))
260 #' emphasize.cols(1)
261 #' emphasize.rows(1)
262 #' pandoc.table(n)
263 #'
264 #' emphasize.strong.cells(which(n == 1, arr.ind = TRUE))
265 #' pander(n)
266 #' }
267 emphasize.rows <- function(x)
268 assign(deparse(match.call()[[1]]), x, envir = storage)
269 #' @export
270 emphasize.strong.rows <- emphasize.rows
271 #' @export
272 emphasize.italics.rows <- emphasize.rows
273 #' @export
274 emphasize.verbatim.rows <- emphasize.rows
275 #' @export
276 emphasize.cols <- emphasize.rows
277 #' @export
278 emphasize.strong.cols <- emphasize.rows
279 #' @export
280 emphasize.italics.cols <- emphasize.rows
281 #' @export
282 emphasize.verbatim.cols <- emphasize.rows
283 #' @export
284 emphasize.cells <- emphasize.rows
285 #' @export
286 emphasize.strong.cells <- emphasize.rows
287 #' @export
288 emphasize.italics.cells <- emphasize.rows
289 #' @export
290 emphasize.verbatim.cells <- emphasize.rows
291
292
293 #' Get emphasize params from internal buffer
294 #'
295 #' And truncate content.
296 #' @param df tabular data
297 #' @return R object passed as \code{df} with possibly added \code{attr}s captured from internal buffer
298 #' @keywords internal
299 get.emphasize <- function(df) {
300 for (v in c('emphasize.rows',
301 'emphasize.cols',
302 'emphasize.cells',
303 'emphasize.strong.rows',
304 'emphasize.strong.cols',
305 'emphasize.strong.cells',
306 'emphasize.italics.rows',
307 'emphasize.italics.cols',
308 'emphasize.italics.cells',
309 'emphasize.verbatim.rows',
310 'emphasize.verbatim.cols',
311 'emphasize.verbatim.cells')) {
312 if (is.null(attr(df, v))) {
313 attr(df, v) <- get.storage(v)
314 }
315 }
316 return(df)
317 }
318
319
320 #' Get a value from internal buffer
321 #'
322 #' And truncate content.
323 #' @param what string
324 #' @keywords internal
325 get.storage <- function(what) {
326 res <- tryCatch(get(what, envir = storage, inherits = FALSE), error = function(e) NULL)
327 if (is.null(attr(res, 'permanent')) || !attr(res, 'permanent')) {
328 assign(what, NULL, envir = storage)
329 }
330 return(res)
331 }
332
333
334 #' Add significance stars
335 #'
336 #' This function adds significance stars to passed \code{p} value(s) as: one star for value below \code{0.05}, two for \code{0.01} and three for \code{0.001}.
337 #' @param p numeric vector or tabular data
338 #' @param cutoffs the cutoffs for the 1/2/3 significance stars
339 #' @return character vector
340 #' @export
341 add.significance.stars <- function(p, cutoffs = c(0.05, 0.01, 0.001)) {
342
343 stopifnot(length(cutoffs) == 3)
344
345 if (inherits(p, c('matrix', 'data.frame')) && length(dim(p)) == 2) {
346 apply(p, c(1,2), add.significance.stars, cutoffs = cutoffs)
347 } else {
348 if (length(p) > 1) {
349 sapply(p, add.significance.stars, cutoffs = cutoffs)
350 } else {
351 ifelse(p > cutoffs[1], '',
352 ifelse(p > cutoffs[2], ' *',
353 ifelse(p > cutoffs[3], ' * *', ' * * *')))
354 }
355 }
356 }
357
358
359 #' Toggle cache
360 #'
361 #' This function is just a wrapper around \code{\link{evalsOptions}} to switch pander's cache on or off easily, which might be handy in some brew documents to prevent repetitive strain injury :)
362 #' @aliases cache.on
363 #' @usage
364 #' cache.on()
365 #'
366 #' cache.off()
367 #' @export
368 cache.off <- function()
369 evalsOptions('cache', FALSE)
370
371 #' @export
372 cache.on <- function()
373 evalsOptions('cache', TRUE)
374
375 #' Split line with line breaks depending on max.width
376 #'
377 #' This is a helper function to insert line breaks depending on (\code{split.cells} parameter of \code{pandoc.table}) of the returning table.
378 #' @param x string to be split. Works only with one string. Non-string arguments and multi-dimensional arguments are returned unchanged
379 #' @param max.width default integer value specifying max number of characters between line breaks
380 #' @param use.hyphening (default: \code{FALSE}) if try to use hyphening when splitting large cells according to table.split.cells. Requires \pkg{sylly}.
381 #' @return character string with line breaks
382 #' @export
383 #' @examples
384 #' splitLine('foo bar', 6)
385 #' splitLine('foo bar', 7)
386 #' splitLine('Pandoc Package', 3, TRUE)
387 splitLine <- function(x, max.width = panderOptions('table.split.cells'), use.hyphening = FALSE) {
388 if (any(is.na(x))) {
389 return(x)
390 }
391 if (!is.character(x) || !is.null(dim(x)) || length(x) != 1 || x == '') {
392 return(x)
393 }
394 if (suppressWarnings(!is.na(as.numeric(x)))) {
395 return(x)
396 }
397 if (is.infinite(max.width)) {
398 max.width <- .Machine$integer.max
399 }
400 if (use.hyphening) {
401 if (requireNamespace('sylly', quietly = TRUE) && requireNamespace('sylly.en', quietly = TRUE)) {
402 sylly.en::hyph.support.en()
403 } else {
404 use.hyphening <- FALSE
405 }
406 }
407 hyphen_f <- function(s)
408 sylly::hyphen(s, hyph.pattern = 'en', quiet = TRUE)@hyphen[1, 2]
409 splitLine_cpp(x, max.width, use.hyphening, hyphen_f)
410 }
411
412
413 #' Check if caption is valid
414 #' @param caption R object to check
415 #' @return boolean
416 #' @keywords internal
417 check_caption <- function(caption) {
418
419 if (length(caption) > 1) {
420 stop('The caption should be exactly one string.')
421 }
422
423 if (!(is.character(caption) | is.null(caption))){
424 stop('The caption should be string (character class) or NULL.')
425 }
426 invisible(TRUE)
427 }
428
429
430 #' Check if vector parameter for round/digits and adjust accodingly
431 #' @param param vector to be checked
432 #' @param name parameter name
433 #' @param n needed size of vector
434 #' @return original vector if size is good, vector of default values otherwise
435 #' @keywords internal
436 check_digits <- function(param, name, n) {
437 if (length(param) == 1) {
438 param <- rep(param, n)
439 } else if (length(param) < n) {
440 warning(sprintf('%s is not equal to ncol(t), reverting to default value', name))
441 param <- rep(panderOptions(name), n)
442 }
443 param
444 }
445
446 #' Create a multitable used for rendering objects from rms package
447 #'
448 #' When ols/lrm/orm from rms package get rendered, main statistics are group in table of tables.
449 #' Since pandoc doesn't support row or col-span,
450 #' we chose to group those statistics in a column each.
451 #' This function takes care of that
452 #' @param v list of vectors/lists to be merge in the table
453 #' @return data.frame in specified format
454 #' @examples
455 #' pander:::multitable(list(list(a=1, b=2),list(c=3, d=4)))
456 #' @keywords internal
457 multitable <- function(v) {
458 ml <- max(sapply(v, length))
459 mod <- lapply(1:length(v),
460 function(i) {
461 uv <- unlist(c(rbind(pandoc.strong.return(names(v[[i]])),
462 sapply(v[[i]], p, wrap = ''))))
463 if (length(v[[i]]) < ml)
464 uv <- c(uv, rep('', 2 * (ml - length(v[[i]]))))
465 uv
466 })
467 do.call(cbind, mod)
468 }
469
470 #' Calculate coef matrix for models from rms package
471 #' Forked from prModFit from rms
472 #'
473 #' @param obj object list
474 #' @param coefs numeric value if to print only the first n regression coefficients in the model.
475 #' @return coeficients matrix
476 #' @importFrom stats pt pchisq
477 coef_mat <- function(obj, coefs) {
478 errordf <- obj$errordf
479 beta <- obj$coef
480 se <- obj$se
481 Z <- beta / se
482 if (length(errordf)) {
483 P <- 2 * (1 - pt(abs(Z), errordf))
484 } else {
485 P <- 1 - pchisq(Z ^ 2, 1)
486 }
487 U <- cbind(beta, se, Z, P)
488 colnames(U) <- c('Coef', 'S.E.', 'Wald Z', 'Pr(>|Z|)')
489 if (length(errordf)) {
490 colnames(U)[3:4] <- c('t', 'Pr(>|t|)')
491 }
492 rownames(U) <- names(beta)
493 if (length(obj$aux)) {
494 U <- cbind(U, obj$aux)
495 colnames(U)[ncol(U)] <- obj$auxname
496 }
497 if (is.numeric(coefs)) {
498 U <- U[1:coefs, , drop = FALSE] #nolint
499 U <- rbind(U, rep('', ncol(U)))
500 rownames(U)[nrow(U)] <- '. . .'
501 }
502 U
503 }
504
505
506 #' Find path to the pandoc binary by checking the \code{PATH} and the \code{RSTUDIO_PANDOC} env vars
507 #' @return file path
508 #' @export
509 path_to_pandoc <- function() {
510
511 ## check if pandoc can be found on the path
512 bin <- as.character(Sys.which('pandoc'))
513
514 ## check RStudio env var pointing to the bundled pandoc
515 if (Sys.getenv('RSTUDIO_PANDOC') != '') {
516 bin <- Sys.getenv('RSTUDIO_PANDOC')
517 bin <- file.path(bin, ifelse(
518 grepl('w|W', .Platform$OS.type),
519 ## we are on Windows
520 'pandoc.exe',
521 ## no extension on Mac and Linux
522 'pandoc'))
523 }
524
525 ## return whatever found
526 bin
527
528 }