Debian Codegraph @

R/S3.R

raw
1 #' Generic pander method
2 #'
3 #' Prints an R object in Pandoc's markdown.
4 #' @param x an R object
5 #' @param ... optional parameters passed to special methods and/or raw \code{pandoc.*} functions
6 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
7 #' @note This function can be called by \code{pander} and \code{pandoc} too.
8 #' @references \itemize{
9 #' \item John MacFarlane (2013): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
10 #' \item David Hajage (2011): _ascii. Export R objects to several markup languages._ \url{https://cran.r-project.org/package=ascii}
11 #' \item Hlavac, Marek (2013): _stargazer: LaTeX code for well-formatted regression and summary statistics tables._ \url{https://cran.r-project.org/package=stargazer}
12 #' }
13 #' @export
14 #' @examples
15 #'
16 #' ## Vectors
17 #' pander(1:10)
18 #' pander(letters)
19 #' pander(mtcars$am)
20 #' pander(factor(mtcars$am))
21 #'
22 #' ## Lists
23 #' pander(list(1, 2, 3, c(1, 2)))
24 #' pander(list(a = 1, b = 2, c = table(mtcars$am)))
25 #' pander(list(1, 2, 3, list(1, 2)))
26 #' pander(list(a = 1, 2, 3, list(1, 2)))
27 #' pander(list('FOO', letters[1:3], list(1:5), table(mtcars$gear), list('FOOBAR', list('a', 'b'))))
28 #' pander(list(a = 1, b = 2, c = table(mtcars$am), x = list(myname = 1, 2), 56))
29 #' pander(unclass(chisq.test(table(mtcars$am, mtcars$gear))))
30 #'
31 #' ## Arrays
32 #' pander(mtcars)
33 #' pander(table(mtcars$am))
34 #' pander(table(mtcars$am, mtcars$gear))
35 #'
36 #' ## Tests
37 #' pander(ks.test(runif(50), runif(50)))
38 #' pander(chisq.test(table(mtcars$am, mtcars$gear)))
39 #' pander(t.test(extra ~ group, data = sleep))
40 #'
41 #' ## Models
42 #' ml <- with(lm(mpg ~ hp + wt), data = mtcars)
43 #' pander(ml)
44 #' pander(anova(ml))
45 #' pander(aov(ml))
46 #' ## Dobson (1990) Page 93: Randomized Controlled Trial (examples from: ?glm)
47 #' counts <- c(18, 17, 15, 20, 10, 20, 25, 13, 12)
48 #' outcome <- gl(3, 1, 9)
49 #' treatment <- gl(3, 3)
50 #' m <- glm(counts ~ outcome + treatment, family = poisson())
51 #' pander(m)
52 #' pander(anova(m))
53 #' pander(aov(m))
54 #' ## overwriting labels
55 #' pander(lm(Sepal.Width ~ Species, data = iris), covariate.labels = c('Versicolor', 'Virginica'))
56 #'
57 #' ## Prcomp
58 #' pander(prcomp(USArrests))
59 #'
60 #' ## Others
61 #' pander(density(runif(10)))
62 #' pander(density(mtcars$hp))
63 #'
64 #' ## default method
65 #' x <- chisq.test(table(mtcars$am, mtcars$gear))
66 #' class(x) <- 'I heave never heard of!'
67 #' pander(x)
68 pander <- function(x = NULL, ...) {
69
70 ## save current knitr.auto.asis option
71 kaao <- panderOptions('knitr.auto.asis')
72
73 if (isTRUE(panderOptions('knitr.auto.asis')) &&
74 isTRUE(getOption('knitr.in.progress')) &&
75 requireNamespace('knitr', quietly = TRUE)) {
76
77 ## override knitr.auto.asis option for nested calls
78 panderOptions('knitr.auto.asis', FALSE)
79
80 ## grab stdout
81 stdout <- vector('character')
82 con <- textConnection('stdout', 'wr', local = TRUE)
83 sink(con)
84 sink(con, type = 'message')
85
86 ## close
87 on.exit({
88
89 ## restore knitr.auto.asis option
90 if (panderOptions('knitr.auto.asis') != kaao) {
91 panderOptions('knitr.auto.asis', kaao)
92 }
93
94 ## revert R output back to normal
95 sink()
96 sink(type = 'message')
97 close(con)
98
99 ## restore the final line break
100 if (tail(stdout, 1) == '') {
101 stdout <- c(stdout, '')
102 }
103
104 return(knitr::asis_output(paste(stdout, collapse = '\n')))
105 })
106 }
107
108 UseMethod('pander', x)
109
110 }
111
112
113 #' Pander and capture output
114 #'
115 #' This is a wrapper function around \code{pander} but instead of printing to \code{stdout}, this function returns a character vector of the captured lines.
116 #' @param ... everything passed to \code{pander}
117 #' @export
118 #' @seealso pander
119 pander_return <- function(...)
120 capture.output(pander(...))
121
122
123 #' Pander method for a NULL object
124 #'
125 #' Prints a NULL object in Pandoc's markdown.
126 #' @param x a NULL object
127 #' @param ... ignored parameters
128 #' @export
129 pander.NULL <- function(x, ...)
130 return(invisible(NULL))
131
132
133 #' Helper function to deal with atomic vectors
134 #' @param x vector
135 #' @param ... ignored parameters
136 #' @keywords internal
137 #' @export
138 pander.vector <- function(x, ...) {
139
140 if (!is.null(names(x))) {
141 return(pandoc.table(x))
142 }
143
144 cat(p(x))
145
146 }
147
148
149 #' Pander method for logical class
150 #'
151 #' Prints a logical object in Pandoc's markdown.
152 #' @param x a logical object
153 #' @param ... ignored parameters
154 #' @export
155 pander.logical <- function(x, ...)
156 pander.vector(x, ...)
157
158
159 #' Pander method for numeric class
160 #'
161 #' Prints a numeric class in Pandoc's markdown.
162 #' @param x a numeric object
163 #' @param ... igroned parameter
164 #' @export
165 pander.numeric <- function(x, ...)
166 pander.vector(x, ...)
167
168
169 #' Pander method for factor class
170 #'
171 #' Prints a factor object in Pandoc's markdown.
172 #' @param x a factor object
173 #' @param ... igroned parameters
174 #' @export
175 pander.factor <- function(x, ...)
176 pander.vector(x, ...)
177
178
179 #' Pander method for character class
180 #'
181 #' Prints a character class in Pandoc's markdown.
182 #' @param x a character object
183 #' @param ... igroned parameters
184 #' @export
185 pander.character <- function(x, ...) {
186
187 if (!is.null(names(x))) {
188 return(pandoc.table(x))
189 }
190
191 if (length(x) < 2) {
192 cat(x)
193 } else {
194 cat(p(x))
195 }
196
197 }
198
199
200 #' Pander method for image class
201 #'
202 #' Prints a image object in Pandoc's markdown.
203 #' @param x a image object
204 #' @param caption caption (string) to be shown under the table
205 #' @param href link that image should be linked with
206 #' @param ... ignored parameters
207 #' @export
208 pander.image <- function(x, caption = attr(x, 'caption'), href = attr(x, 'href'), ...) {
209
210 if (is.null(caption) & !is.null(storage$caption)) {
211 caption <- get.caption()
212 }
213
214 res <- pandoc.image.return(as.character(x), caption)
215
216 if (is.null(href)) {
217 cat(res)
218 } else {
219 pandoc.link(href, res)
220 }
221
222 }
223
224
225 #' Pander method for table class
226 #'
227 #' Prints a table object in Pandoc's markdown.
228 #' @param x a table object
229 #' @param caption caption (string) to be shown under the table
230 #' @param ... optional parameters passed to raw \code{pandoc.table} function
231 #' @export
232 pander.table <- function(x, caption = attr(x, 'caption'), ...) {
233
234 if (is.null(caption) & !is.null(storage$caption)) {
235 caption <- get.caption()
236 }
237
238 pandoc.table(x, caption = caption, ...)
239
240 }
241
242 #' Pander method for data.table class
243 #'
244 #' Prints a data.table object in Pandoc's markdown. Data.tables drop attributes (like row names) when called.
245 #' @param x a data.table object
246 #' @param caption caption (string) to be shown under the table
247 #' @param keys.as.row.names controls whether to use data.table key as row names when calling pandoc.table
248 #' @param ... optional parameters passed to raw \code{pandoc.table} function
249 #' @export
250 pander.data.table <- function(x, caption = attr(x, 'caption'),
251 keys.as.row.names = TRUE, ...) {
252
253 if (is.null(caption) & !is.null(storage$caption)) {
254 caption <- get.caption()
255 }
256
257 requireNamespace('data.table', quietly = TRUE)
258 xx <- data.table::copy(x)
259 if (keys.as.row.names && data.table::haskey(xx)) {
260 firstkey <- data.table::key(xx)[1]
261 row.names.dt <- as.character(xx[[firstkey]])
262 xx <- xx[, setdiff(colnames(xx), firstkey), with = FALSE, drop = FALSE]
263 data.table::setattr(xx, 'row.names', row.names.dt)
264 }
265
266 pandoc.table(xx, caption = caption, ...)
267
268 }
269
270 #' Pander method for data.frame class
271 #'
272 #' Prints a data.frame object in Pandoc's markdown.
273 #' @param x a data.frame object
274 #' @param caption caption (string) to be shown under the table
275 #' @param ... optional parameters passed to raw \code{pandoc.table} function
276 #' @export
277 pander.data.frame <- function(x, caption = attr(x, 'caption'), ...) {
278
279 if (is.null(caption) & !is.null(storage$caption)) {
280 caption <- get.caption()
281 }
282
283 pandoc.table(x, caption = caption, ...)
284
285 }
286
287
288 #' Pander method for matrix class
289 #'
290 #' Prints a matrix object in Pandoc's markdown.
291 #' @param x a matrix object
292 #' @param caption caption (string) to be shown under the table
293 #' @param ... optional parameters passed to raw \code{pandoc.table} function
294 #' @export
295 pander.matrix <- function(x, caption = attr(x, 'caption'), ...) {
296 if (is.null(caption) & !is.null(storage$caption)) {
297 caption <- get.caption()
298 }
299 pandoc.table(x, caption = caption, ...)
300 }
301
302
303 #' Pander method for cast_df class
304 #'
305 #' Prints a cast_df object in Pandoc's markdown.
306 #' @param x a cast_df object
307 #' @param caption caption (string) to be shown under the table
308 #' @param ... optional parameters passed to raw \code{pandoc.table} function
309 #' @export
310 pander.cast_df <- function(x, caption = attr(x, 'caption'), ...) {
311
312 if (is.null(caption) & !is.null(storage$caption)) {
313 caption <- get.caption()
314 }
315
316 pandoc.table(as.data.frame(x), caption = caption, ...)
317
318 }
319
320
321 #' Pander method for summary.lm class
322 #'
323 #' Prints a summary.lm object in Pandoc's markdown.
324 #' @param x an summary.lm object
325 #' @param caption caption (string) to be shown under the table
326 #' @param covariate.labels vector to replace covariate lables in the table
327 #' @param omit vector of variable to omit for priting in resulting table
328 #' @param summary (defaut:\code{TRUE}) if used for summary.lm or lm
329 #' @param add.significance.stars if significance stars should be shown for P value
330 #' @param move.intercept by default, the Intercept is the first coefficient in the table, which can be moved to the bottom of the table
331 #' @param ... optional parameters passed to special methods and/or raw \code{pandoc.*} functions
332 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
333 #' @export
334 pander.summary.lm <- function(x, caption = attr(x, 'caption'), covariate.labels,
335 omit, summary = TRUE, add.significance.stars = FALSE, move.intercept = FALSE, ...) {
336
337 if (is.null(caption)) {
338 if (is.null(storage$caption)) {
339 caption <- pandoc.formula.return(x$call$formula, text = 'Fitting linear model:')
340 } else {
341 caption <- get.caption()
342 }
343 }
344
345 res <- as.data.frame(x$coefficients)
346
347 if (move.intercept && rownames(res)[1] == '(Intercept)' & nrow(res) > 1) {
348 res <- res[c(2:nrow(res), 1), ]
349 }
350
351 if (!missing(omit)) {
352 res <- res[!apply(sapply(omit, grepl, row.names(res)), 1, any), ]
353 }
354
355 if (!missing(covariate.labels)) {
356 row.names(res)[1:length(covariate.labels)] <- covariate.labels
357 }
358
359 if (add.significance.stars) {
360 res <- cbind(res, ' ' = add.significance.stars(res[, 4]))
361 }
362
363 if (summary) {
364 pandoc.table(res, ...)
365 if (inherits(x, 'summary.glm')) {
366 cat('\n(Dispersion parameter for ', x$family$family, ' family taken to be ',
367 format(x$dispersion), ')\n\n')
368 stats <- cbind(paste(format(c('Null', 'Residual'), justify = 'right'), 'deviance:'),
369 apply(cbind(
370 format(unlist(x[c('null.deviance', 'deviance')]), digits = panderOptions('digits')),
371 ' on',
372 format(unlist(x[c('df.null', 'df.residual')])), ' degrees of freedom\n'),
373 1L, paste, collapse = ' '))
374 rownames(stats) <- NULL
375 colnames(stats) <- NULL
376 pandoc.table(stats, keep.trailing.zeros = TRUE, ...)
377 } else {
378 pandoc.table(data.frame(
379 'Observations' = length(x$residuals),
380 'Residual Std. Error' = x$sigma,
381 '$R^2$' = x$r.squared,
382 'Adjusted $R^2$' = x$adj.r.squared,
383 check.names = FALSE), keep.trailing.zeros = TRUE, caption = caption, digits = panderOptions('digits'))
384 }
385 } else {
386
387 pandoc.table(res, caption = caption, ...)
388
389 }
390
391 }
392
393
394 #' Pander method for summary.glm class
395 #'
396 #' Prints a summary.glm object in Pandoc's markdown.
397 #' @param x an summary.glm object
398 #' @param caption caption (string) to be shown under the table
399 #' @param covariate.labels vector to replace covariate lables in the table
400 #' @param omit vector of variable to omit for priting in resulting table
401 #' @param summary (defaut:\code{TRUE}) if used for summary.lm or lm
402 #' @param ... optional parameters passed to special methods and/or raw \code{pandoc.*} functions
403 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
404 #' @export
405 pander.summary.glm <- function(x, caption = attr(x, 'caption'), covariate.labels, omit, summary = TRUE, ...)
406 pander.summary.lm(x, caption = caption, summary = summary, covariate.labels = covariate.labels, omit = omit, ...)
407
408
409 #' Pander method for summary.lm class
410 #'
411 #' Prints a summary.lm object in Pandoc's markdown.
412 #' @param x a summary.glm object
413 #' @param caption caption (string) to be shown under the table
414 #' @param covariate.labels vector to replace covariate lables in the table
415 #' @param omit vector of variable to omit for priting in resulting table
416 #' @param ... optional parameters passed to raw \code{pandoc.table} function
417 #' @export
418 pander.lm <- function(x, caption = attr(x, 'caption'), covariate.labels, omit, ...)
419 pander.summary.lm(summary(x),
420 caption = caption,
421 summary = FALSE,
422 covariate.labels = covariate.labels,
423 omit = omit, ...)
424
425
426 #' Pander method for summary.glm class
427 #'
428 #' Prints a summary.glm object in Pandoc's markdown.
429 #' @param x a summary.glm object
430 #' @param caption caption (string) to be shown under the table
431 #' @param ... optional parameters passed to raw \code{pandoc.table} function
432 #' @export
433 pander.glm <- function(x, caption = attr(x, 'caption'), ...) {
434
435 if (is.null(caption)) {
436 if (is.null(storage$caption)) {
437 caption <- sprintf('Fitting generalized (%s) linear model: %s',
438 paste(x$family$family, x$family$link, sep = '/'),
439 pandoc.formula.return(x$call$formula))
440 } else {
441 caption <- get.caption()
442 }
443 }
444
445 pander.summary.glm(summary(x), caption = caption, summary = FALSE, ...)
446
447 }
448
449
450 #' Pander method for summary.aov class
451 #'
452 #' Prints a summary.aov object in Pandoc's markdown.
453 #' @param x a summary.aov object
454 #' @param caption caption (string) to be shown under the table
455 #' @param ... optional parameters passed to raw \code{pandoc.table} function
456 #' @export
457 pander.summary.aov <- function(x, caption = attr(x, 'caption'), ...) {
458
459 res <- unclass(x)[[1]]
460
461 if (is.null(caption)) {
462 if (is.null(storage$caption)) {
463 caption <- 'Analysis of Variance Model'
464 } else {
465 caption <- get.caption()
466 }
467 }
468
469 pandoc.table(res, caption = caption, ...)
470 }
471
472
473 #' Pander method for aov class
474 #'
475 #' Prints an aov object in Pandoc's markdown.
476 #' @param x an aov object
477 #' @param caption caption (string) to be shown under the table
478 #' @param ... optional parameters passed to raw \code{pandoc.table} function
479 #' @export
480 pander.aov <- function(x, caption = attr(x, 'caption'), ...) {
481 pander(summary(x), caption = caption, ...)
482 }
483
484
485 #' Pander method for anova class
486 #'
487 #' Prints an anova object in Pandoc's markdown.
488 #' @param x an anova object
489 #' @param caption caption (string) to be shown under the table
490 #' @param add.significance.stars if significance stars should be shown for P value
491 #' @param ... optional parameters passed to raw \code{pandoc.table} function
492 #' @export
493 pander.anova <- function(x, caption = attr(x, 'caption'), add.significance.stars = FALSE, ...) {
494
495 if (is.null(caption)) {
496 if (is.null(storage$caption)) {
497 if (!is.null(attr(x, 'heading'))) {
498 caption <- strsplit(attr(x, 'heading'), '\n')[[1]][1]
499 }
500 }
501 }
502 if (is.null(caption)) {
503 caption <- get.caption()
504 }
505 if (add.significance.stars) {
506 x <- cbind(x, ' ' = add.significance.stars(x[, 5]))
507 }
508 pandoc.table(x, caption = caption, ...)
509 if (add.significance.stars) {
510 cat('Signif. codes: 0 \'\\*\\*\\*\' 0.001 \'\\*\\*\' 0.01 \'\\*\' 0.05 \'.\' 0.1 \' \' 1\n')
511 }
512 }
513
514
515 #' Pander method for summary.aovlist class
516 #'
517 #' Prints a summary.aovlist object in Pandoc's markdown.
518 #' @param x a summary.aovlist object
519 #' @param caption caption (string) to be shown under the table
520 #' @param ... optional parameters passed to raw \code{pandoc.table} function
521 #' @export
522 pander.summary.aovlist <- function(x, caption = attr(x, 'caption'), ...) {
523 n <- length(x)
524 if (n == 1) {
525 pandoc.table(unclass(x[[1]][[1]]), caption, ...)
526 } else {
527 z <- x[[1]][[1]]
528 for (i in 2:n) {
529 z <- rbind(z, x[[i]][[1]])
530 }
531 pandoc.table(z, caption = caption, ...)
532 }
533 }
534
535
536 #' Pander method for aovlist class
537 #'
538 #' Prints an aovlist object in Pandoc's markdown.
539 #' @param x an aovlist object
540 #' @param caption caption (string) to be shown under the table
541 #' @param ... optional parameters passed to raw \code{pandoc.table} function
542 #' @export
543 pander.aovlist <- function(x, caption = attr(x, 'caption'), ...) {
544 pander(summary(x), caption = caption, ...)
545 }
546
547
548 #' Pander method for htest class
549 #'
550 #' Prints a htest object in Pandoc's markdown.
551 #' @param x a htest object
552 #' @param caption caption (string) to be shown under the table
553 #' @param ... optional parameters passed to raw \code{pandoc.table} function
554 #' @export
555 pander.htest <- function(x, caption = attr(x, 'caption'), ...) {
556
557 if (is.null(caption)) {
558 if (is.null(storage$caption)) {
559 caption <- paste0(x$method, ': `', gsub('( and | by )', '`\\1`', paste(x$data.name, collapse='')), '`')
560 } else {
561 caption <- get.caption()
562 }
563 }
564
565 ## we do not know which values are provided
566 res <- data.frame(placeholder = 'FOO')
567
568 ## add what we know
569 if (!is.null(x$statistic)) {
570 res$'Test statistic' <- as.numeric(x$statistic)
571 }
572 if (!is.null(x$parameter)) {
573 res[names(x$parameter)] <- x$parameter
574 }
575 if (!is.null(x$p.value)) {
576 res$'P value' <- paste(
577 format(round(x$p.value, panderOptions('round')),
578 trim = TRUE,
579 digits = panderOptions('digits'),
580 decimal.mark = panderOptions('decimal.mark')),
581 add.significance.stars(x$p.value))
582 }
583 if (!is.null(x$alternative)) {
584 res['Alternative hypothesis'] <- x$alternative
585 }
586 if (!is.null(x$estimate)) {
587 if (!is.null(names(x$estimate))) {
588 res[names(x$estimate)] <- x$estimate
589 } else {
590 res['Estimate'] <- x$estimate
591 }
592 }
593
594 ## drop placeholder
595 res$placeholder <- NULL
596
597 ## return
598 pandoc.table(res, caption = caption, ...)
599
600 }
601
602
603 #' Pander method for summary.prcomp class
604 #'
605 #' Prints a summary.prcomp object in Pandoc's markdown.
606 #' @param x a summary.prcomp object
607 #' @param caption caption (string) to be shown under the table
608 #' @param summary (default:\code{TRUE}) if extended summary should be printed
609 #' @param ... optional parameters passed to raw \code{pandoc.table} function
610 #' @export
611 pander.summary.prcomp <- function(x, caption = attr(x, 'caption'), summary = TRUE, ...) {
612
613 if (is.null(caption)) {
614 if (is.null(storage$caption)) {
615 caption <- 'Principal Components Analysis'
616 } else {
617 caption <- get.caption()
618 }
619 }
620
621 pandoc.table(x$rotation, caption = caption, ...)
622 if (summary) {
623 pandoc.table(x$importance, ...)
624 }
625 }
626
627
628 #' Pander method for prcomp class
629 #'
630 #' Prints a prcomp object in Pandoc's markdown.
631 #' @param x a prcomp object
632 #' @param caption caption (string) to be shown under the table
633 #' @param ... optional parameters passed to raw \code{pandoc.table} function
634 #' @export
635 pander.prcomp <- function(x, caption = attr(x, 'caption'), ...) {
636 pander(summary(x), caption = caption, summary = FALSE, ...)
637 }
638
639
640 #' Pander method for density class
641 #'
642 #' Prints a density object in Pandoc's markdown.
643 #' @param x a density object
644 #' @param caption caption (string) to be shown under the table
645 #' @param ... optional parameters passed to raw \code{pandoc.table} function
646 #' @export
647 pander.density <- function(x, caption = attr(x, 'caption'), ...) {
648
649 if (is.null(caption)) {
650 if (is.null(storage$caption)) {
651 caption <- sprintf('Kernel density of *%s* (bandwidth: %s)', x$data.name, format(x$bw))
652 } else {
653 caption <- get.caption()
654 }
655 }
656
657 res <- data.frame('Coordinates' = as.numeric(summary(x$x)),
658 'Density values' = as.numeric(summary(x$y)),
659 check.names = FALSE)
660 rownames(res) <- names(summary(1))
661
662 pandoc.table(res, caption = caption, ...)
663 }
664
665
666 #' Pander method for list class
667 #'
668 #' Prints a list object in Pandoc's markdown.
669 #' @param x a list object
670 #' @param ... ignored parameters
671 #' @export
672 pander.list <- function(x, ...) {
673
674 ## early exit on no values
675 if (length(x) == 0) {
676 return(pander(NULL))
677 }
678
679 ## match call
680 mc <- match.call()
681 if (is.null(mc$indent)) {
682 indent <- 0
683 } else {
684 indent <- eval(mc$indent, parent.frame(1))
685 }
686
687 ## replace missing values
688 w <- which(is.na(x))
689 if (length(w) > 0) {
690 x[w] <- panderOptions('missing')
691 }
692
693 ## grab elements name (if any)
694 x.names <- sapply(names(x), function(x) ifelse(x == '', ' *', sprintf(' * **%s**:', x)))
695 if (length(x.names) == 0) {
696 x.names <- rep(' *', length(x))
697 }
698
699 ## capture pandoc output of list element
700 res <- paste(unlist(lapply(1:length(x), function(i) {
701
702 res.i <- paste(capture.output(pander(x[[i]], indent = 1)), collapse = '\n')
703 if (grepl('\n', res.i) & !grepl('\n *\\* ', res.i)) {
704 res.i <- sub('^\n', '\n\n', res.i)
705 res.i <- pandoc.indent(res.i, 1)
706 }
707
708 paste(x.names[i], res.i)
709
710 })), collapse = '\n') #nolint
711
712 ## indent output
713 res <- pandoc.indent(res, indent)
714
715 ## add (comment): end of list (preventing conflicts with forthcoming pandoc blocks)
716 if (indent == 0) {
717 res <- paste0(res, '\n\n<!-- end of list -->\n')
718 }
719
720 pandoc.p(res)
721
722 }
723
724
725 #' Default Pander method
726 #'
727 #' Method to be used, when no exact S3 method for given object is found. Tries to render object as a list
728 #' @param x an object
729 #' @param ... optional parameters passed to raw \code{pandoc.list} function
730 #' @export
731 pander.default <- function(x, ...) {
732 warning(sprintf('No pander.method for "%s", reverting to default.', class(x)))
733 class(x) <- 'list'
734 pander(x, ...)
735 }
736
737
738 #' Pander method for evals class
739 #'
740 #' Prints a evals object in Pandoc's markdown.
741 #' @param x a evals object
742 #' @param ... ignored parameters
743 #' @export
744 pander.evals <- function(x, ...) {
745
746 o <- pander(x$result)
747
748 if (panderOptions('evals.messages')) {
749 if (!is.null(x$msg$messages)) {
750 o <- paste0(o, ' **MESSAGE**', pandoc.footnote.return(x$msg$messages))
751 }
752 if (!is.null(x$msg$warnings)) {
753 o <- paste0(o, ' **WARNING**', pandoc.footnote.return(x$msg$warnings))
754 }
755 if (!is.null(x$msg$error)) {
756 o <- paste0(o, ' **ERROR**', pandoc.footnote.return(x$msg$errors))
757 }
758 }
759
760 cat(o)
761
762 }
763
764
765 #' Pander method for rapport class
766 #'
767 #' Prints a rapport object in Pandoc's markdown.
768 #' @param x a rapport object
769 #' @param ... ignored parameters
770 #' @export
771 pander.rapport <- function(x, ...)
772 print(x)
773
774
775 #' Pander method for POSIXlt class
776 #'
777 #' Prints a POSIXlt object in Pandoc's markdown.
778 #' @param x a POSIXlt object
779 #' @param ... optional parameters passed to raw \code{pandoc.date} function
780 #' @export
781 pander.POSIXlt <- function(x, ...)
782 pandoc.date(x, ...)
783
784
785 #' Pander method for POSIXct class
786 #'
787 #' Prints a POSIXct object in Pandoc's markdown.
788 #' @param x a POSIXct object
789 #' @param ... optional parameters passed to raw \code{pandoc.date} function
790 #' @export
791 pander.POSIXct <- function(x, ...)
792 pandoc.date(x, ...)
793
794
795 #' Pander method for Date class
796 #'
797 #' Prints a Date object in Pandoc's markdown.
798 #' @param x a Date object
799 #' @param ... optional parameters passed to raw \code{pandoc.date} function
800 #' @export
801 pander.Date <- function(x, ...)
802 pandoc.date(x, ...)
803
804
805 #' Pander method for ftable class
806 #'
807 #' Prints a ftable object in Pandoc's markdown.
808 #' @param x a ftable object
809 #' @param ... optional parameters passed to raw \code{pandoc.table} function
810 #' @export
811 pander.ftable <- function(x, ...)
812 pandoc.table(x, ...)
813
814
815 #' Pander method for CrossTable class
816 #'
817 #' Prints a CrossTable object in Pandoc's markdown.
818 #' @param x a CrossTable object
819 #' @param caption caption (string) to be shown under the table
820 #' @param digits number of digits of precision
821 #' @param total.r if to print row totals. Default values is taken from CrossTable object
822 #' @param total.c if to print column totals. Default values is taken from CrossTable object
823 #' @param ... optional parameters passed to raw \code{pandoc.table} function
824 #' @export
825 pander.CrossTable <- function(x, caption = attr(x, 'caption'), digits = panderOptions('digits'),
826 total.r = x$total.r, total.c = x$total.c, ...) {
827 if (is.null(caption) & !is.null(storage$caption)) {
828 caption <- get.caption()
829 }
830 nr <- dim(x$t)[1]
831 nc <- dim(x$t)[2]
832 if (!is.null(rownames(x$t))) {
833 nt <- cbind(rownames(x$t), x$t, x$rs)
834 } else {
835 nt <- cbind('&nbsp;', x$t, x$rs)
836 }
837 hdd <- 100
838 appendlines <- function(nt, xx, hasttl = FALSE, haslbl = FALSE) {
839 if (!hasttl) {
840 xx <- cbind(xx, rep('', nr))
841 }
842 if (!haslbl) {
843 xx <- cbind(rep('', nr), xx)
844 }
845 n <- dim(nt)[1] / nr
846 nt <- rbind(nt, xx)
847 idx <- integer()
848 k <- 1
849 l <- nr * n + 1
850 for (i in 1:nr) {
851 for (j in 1:n) {
852 idx <- c(idx, k)
853 k <- k + 1
854 }
855 idx <- c(idx, l)
856 l <- l + 1
857 }
858 nt <- nt[idx, ]
859 nt
860 }
861 if (!is.na(x$expected) && x$expected == TRUE) {
862 xex <- outer(x$rs, x$cs, '*')
863 xex <- xex / x$gt
864 if (is.null(digits)) {
865 digits <- 1
866 }
867 xx <- format(round(xex, digits), ...)
868 xx <- cbind(rep('Expected N', nr), xx, rep('', nr))
869 nt <- rbind(nt, xx)
870 idx <- integer()
871 for (i in 1:nr) {
872 idx <- c(idx, i, i + nr)
873 }
874 nt <- nt[idx, ]
875 }
876 if (x$prop.chisq) {
877 xx <- (x$CST$expected - x$t) ^ 2 / x$CST$expected
878 xx <- format(round(xx, digits), trim = TRUE, ...)
879 xx <- cbind('Chi-square', xx)
880 nt <- appendlines(nt, xx, haslbl = TRUE)
881 }
882 if (!is.na(x$prop.row[1])) {
883 xx <- cbind(x$prop.row, x$rs / x$gt)
884 xx <- format(round(xx * hdd, digits), trim = TRUE, ...)
885 xx <- matrix(paste(xx, '%', sep = ''), nrow = nr,
886 ncol = nc + 1)
887 xx <- cbind('Row(%)', xx)
888 nt <- appendlines(nt, xx, TRUE, haslbl = TRUE)
889 }
890 if (!is.na(x$prop.col[1])) {
891 xx <- format(round(x$prop.col * hdd, digits), trim = TRUE,
892 ...)
893 xx <- matrix(paste(xx, '%', sep = ''), nrow = nr,
894 ncol = nc)
895 xx <- cbind('Column(%)', xx)
896 nt <- appendlines(nt, xx, haslbl = TRUE)
897 }
898 if (!is.na(x$prop.tbl[1])) {
899 xx <- format(round(x$prop.tbl * hdd, digits), trim = TRUE,
900 ...)
901 xx <- matrix(paste(xx, '%', sep = ''), nrow = nr,
902 ncol = nc)
903 xx <- cbind('Total(%)', xx)
904 nt <- appendlines(nt, xx, haslbl = TRUE)
905 }
906 if (!is.na(x$resid) && x$resid == TRUE && x$expected == TRUE) {
907 xx <- x$t - xex
908 xx <- format(round(xx, digits), trim = TRUE, ...)
909 xx <- cbind('Residual', xx)
910 nt <- appendlines(nt, xx, haslbl = TRUE)
911 }
912 if (!is.na(x$sresid) && x$sresid == TRUE
913 && x$expected == TRUE) {
914 xx <- x$CST$residual
915 xx <- format(round(xx, digits), trim = TRUE, ...)
916 xx <- cbind('Std Residual', xx)
917 nt <- appendlines(nt, xx, haslbl = TRUE)
918 }
919 if (!is.na(x$asr[1])) {
920 xx <- format(round(x$asr, digits), trim = TRUE, ...)
921 xx <- cbind('Adj Std Resid', xx)
922 nt <- appendlines(nt, xx, haslbl = TRUE)
923 }
924 n <- dim(nt)[1] / nr
925 idx <- seq(1, dim(nt)[1], n)
926 nt <- rbind(nt, c(gettext('Total', domain = 'R-descr'), x$cs,
927 x$gt))
928 if (!is.na(x$prop.col[1])) {
929 nt <- rbind(nt, c('', sapply(round(hdd * x$cs / x$gt, digits), function(x) paste(x, '%', sep = '')), ''))
930 }
931 len <- dim(nt)[1]
932 rownames(nt) <- as.character(1:len)
933
934 ## merging and print
935 ts <- ifelse(!is.na(x$prop.col[1]), 2, 1)
936 or <- (nrow(nt) - ts) / nr
937 nt.nr <- nrow(nt)
938 nc <- ncol(nt)
939 if (!is.null(total.r) && !total.r) {
940 nc <- nc - 1
941 }
942 RowData <- x$RowData
943 ColData <- x$ColData
944 res <- NULL
945 for (i in 1:nr) {
946 res.r <- paste(pandoc.strong.return(nt[1 + or * (i - 1), 1]),
947 'N',
948 paste(nt[ (2 + or * (i - 1)) : (i * or), 1], collapse = '\\ \n'),
949 sep = '\\ \n')
950 for (j in 2:nc) {
951 res.r <- cbind(res.r,
952 paste('&nbsp;',
953 paste(nt[ (1 + or * (i - 1)) : (i * or), j], collapse = '\\ \n'),
954 sep = '\\ \n'))
955 }
956 res <- rbind(res, res.r)
957 }
958 res.r <- NULL
959 if (is.null(total.c) || total.c) {
960 for (j in 1:nc) {
961 res.r <- cbind(res.r, paste(nt[ (nt.nr - ts + 1) : nt.nr, j], collapse = '\\ \n'))
962 }
963 res <- rbind(res, res.r)
964 }
965 cln <- c(ifelse(RowData != '', RowData, '&nbsp;'), colnames(x$t))
966 if (is.null(total.r) || total.r) {
967 cln <- c(cln, 'Total')
968 }
969 if (ColData != '') {
970 cln.t <- paste(c('&nbsp;', ColData, rep('&nbsp;', nc - 2)), rep('\\\n', nc - 1), sep = '')
971 cln <- paste(cln.t, cln, sep = '')
972 }
973 colnames(res) <- cln
974 pandoc.table(res, caption = caption, keep.line.breaks = TRUE, ...)
975 }
976
977
978 #' Pander method for timeseries class
979 #'
980 #' Prints a timeseries object in Pandoc's markdown.
981 #' @param x a timeseries object
982 #' @param caption caption (string) to be shown under the table
983 #' @param ... optional parameters passed to raw \code{pandoc.table} function
984 #' @export
985 #' @importFrom stats time cycle frequency start end time
986 pander.ts <- function(x, caption = attr(x, 'caption'), ...) {
987
988 if (is.null(caption) & !is.null(storage$caption)) {
989 caption <- get.caption()
990 }
991
992 if (!is.null(ncol(x))) {
993 tp.1 <- trunc(time(x))
994 tp.2 <- trunc(cycle(x))
995 day.abb <- c('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri',
996 'Sat')
997 row.names <- switch(frequency(x), tp.1, 'Arg2', 'Arg3',
998 paste(tp.1, c('Q1', 'Q2', 'Q3', 'Q4')[tp.2], sep = ' '),
999 'Arg5', 'Arg6', paste('Wk.', tp.1, ' ', day.abb[tp.2],
1000 sep = ''), 'Arg8', 'Arg9', 'Arg10', 'Arg11',
1001 paste(tp.1, month.abb[tp.2], sep = ' '))
1002 t <- data.frame(x, row.names = row.names)
1003 } else {
1004 col.names <- switch(frequency(x), 'Value', 'Arg2', 'Arg3',
1005 c('Q1', 'Q2', 'Q3', 'Q4'), 'Arg5', 'Arg6', day.abb,
1006 'Arg8', 'Arg9', 'Arg10', 'Arg11', month.abb)
1007 row.names <- seq(from = start(x)[1], to = end(x)[1])
1008 t <- data.frame(matrix(c(rep(NA, start(x)[2] - 1),
1009 x, rep(NA, frequency(x) - end(x)[2])), ncol = frequency(x),
1010 byrow = TRUE), row.names = row.names)
1011 names(t) <- col.names
1012 }
1013
1014 pandoc.table(t, caption = caption, ...)
1015
1016 }
1017
1018
1019 #' Pander method for formula class
1020 #'
1021 #' Prints a formula object in Pandoc's markdown.
1022 #' @param x a formula object
1023 #' @param max.width maximum width in characters per line
1024 #' @param caption caption (string) to be shown under the formula
1025 #' @param ... optional parameters passed to raw \code{pandoc.formula} function
1026 #' @export
1027 pander.formula <- function(x, max.width = 80, caption = attr(x, 'caption'), ...) {
1028 if (is.null(caption) & !is.null(storage$caption)) {
1029 caption <- get.caption()
1030 }
1031 pandoc.formula(x, max.width = max.width, caption = caption, ...)
1032 }
1033
1034
1035 #' Pander method for call class
1036 #'
1037 #' Prints a call object in Pandoc's markdown.
1038 #' @param x a call object
1039 #' @param ... optional parameters passed to raw \code{pandoc.formula} function
1040 #' @export
1041 pander.call <- function(x, ...)
1042 pandoc.verbatim(deparse(x))
1043
1044 #' Pander method for name class
1045 #'
1046 #' Prints a call object in Pandoc's markdown.
1047 #' @param x a name language object
1048 #' @param ... ignored parameters
1049 #' @export
1050 pander.name <- function(x, ...)
1051 pander(deparse(x))
1052
1053 #' Pander method for coxph class
1054 #'
1055 #' Prints a coxph object in Pandoc's markdown.
1056 #' @param x an coxph object
1057 #' @param caption caption (string) to be shown under the table
1058 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1059 #' @export
1060 #' @importFrom stats pchisq naprint
1061 pander.coxph <- function(x, caption = attr(x, 'caption'), ...) {
1062
1063 if (is.null(caption)) {
1064 if (is.null(storage$caption)) {
1065 caption <- pandoc.formula.return(x$call$formula, text = 'Fitting Proportional Hazards Regression Model:')
1066 } else {
1067 caption <- get.caption()
1068 }
1069 }
1070
1071 if (!is.null(x$fail)) {
1072 cat(' Coxph failed.', x$fail, '\n')
1073 return(invisible())
1074 }
1075
1076 beta <- x$coef
1077 se <- sqrt(diag(x$var))
1078
1079 if (is.null(x$naive.var)) {
1080 c.tab <- cbind(beta, exp(beta), se, beta / se, 1 - pchisq( (beta / se) ^ 2, 1))
1081 dimnames(c.tab) <- list(names(beta), c('coef', 'exp(coef)', 'se(coef)', 'z', 'p'))
1082 } else {
1083 c.tab <- cbind(beta, exp(beta), se, beta / se, signif(1 - pchisq( (beta / se) ^ 2, 1), 1))
1084 dimnames(c.tab) <- list(names(beta), c('coef', 'exp(coef)', 'robust se', 'z', 'p'))
1085 }
1086
1087 pandoc.table(c.tab, caption = caption, ...)
1088 logtest <- -2 * (x$loglik[1] - x$loglik[2])
1089
1090 if (is.null(x$df)) {
1091 df <- sum(!is.na(beta))
1092 } else {
1093 df <- round(sum(x$df), 2)
1094 }
1095
1096 cat('Likelihood ratio test=', format(round(logtest, 2)), ' on ',
1097 df, ' df,', ' p=', format(1 - pchisq(logtest, df)), sep = '')
1098
1099 omit <- x$na.action
1100 cat(' n=', x$n)
1101 if (!is.null(x$nevent)) {
1102 cat(', number of events=', x$nevent, '\n')
1103 } else {
1104 cat('\n')
1105 }
1106
1107 if (length(omit)) {
1108 cat(' (', naprint(omit), ')\n', sep = '')
1109 }
1110
1111 }
1112
1113
1114 #' Pander method for clogit class
1115 #'
1116 #' Prints a clogit object in Pandoc's markdown.
1117 #' @param x an clogit object
1118 #' @param caption caption (string) to be shown under the table
1119 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1120 #' @export
1121 pander.clogit <- function (x, caption = attr(x, 'caption'), ...) {
1122
1123 if (is.null(caption)) {
1124 if (is.null(storage$caption)) {
1125 caption <- pandoc.formula.return(x$userCall, text = 'Fitting Conditional logistic regression:')
1126 } else {
1127 caption <- get.caption()
1128 }
1129 }
1130
1131 pander.coxph(x, caption = caption, ...)
1132
1133 }
1134
1135
1136 #' Pander method for zoo class
1137 #'
1138 #' Prints a zoo object in Pandoc's markdown.
1139 #' @param x an zoo object
1140 #' @param caption caption (string) to be shown under the table
1141 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1142 #' @export
1143 pander.zoo <- function(x, caption = attr(x, 'caption'), ...) {
1144
1145 if (is.null(caption) & !is.null(storage$caption)) {
1146 caption <- get.caption()
1147 }
1148
1149 c.tab <- as.data.frame(x)
1150 c.tab <- cbind(pandoc.date.return(trunc(time(x)), simplified = TRUE), c.tab)
1151
1152 if (length(colnames(x)) != 0) {
1153 colnames(c.tab) <- c('Period', colnames(x))
1154 } else {
1155 colnames(c.tab) <- c('Period', 'Value')
1156 }
1157
1158 rownames(c.tab) <- NULL
1159 pandoc.table(c.tab, caption = caption, ...)
1160
1161 }
1162
1163 #' Pander method for summary.lme class
1164 #'
1165 #' Prints a lme object in Pandoc's markdown.
1166 #' @param x a lme object
1167 #' @param caption caption (string) to be shown under the table
1168 #' @param summary (default:\code{TRUE}) if to print expender summary
1169 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1170 #' @export
1171 pander.summary.lme <- function(x, caption = attr(x, 'caption'), summary = TRUE, ...) {
1172 if (is.null(caption)) {
1173 if (is.null(storage$caption)) {
1174 caption <- sprintf('Linear mixed-effects model fit by %s : %s',
1175 paste(sub('^[ ]*', '', ifelse(x$method == 'REML', 'REML', 'maximum likelihood'))),
1176 pandoc.formula.return(x$call$fixed), collapse = '')
1177 } else {
1178 caption <- get.caption()
1179 }
1180 }
1181 res <- as.data.frame(x$tTable)
1182 if (summary) {
1183 pandoc.table(res, caption = pandoc.formula.return(x$call$fixed, text = 'Fixed effects: '),
1184 split.tables = Inf, ...)
1185 pandoc.table(x$residuals, caption = 'Standardized Within-Group Residuals')
1186 pandoc.table(data.frame(
1187 'Observations' = x$dims[['N']],
1188 'Groups' = x$dims$ngrps[1:x$dims$Q],
1189 'Log-restricted-likelihood' = x$logLik,
1190 check.names = FALSE), keep.trailing.zeros = TRUE, caption = caption, digits = 4)
1191 } else {
1192 pandoc.table(res, caption = caption, ...)
1193 }
1194 }
1195
1196 #' Pander method for lme class
1197 #'
1198 #' Prints a lme object in Pandoc's markdown.
1199 #' @param x a lme object
1200 #' @param caption caption (string) to be shown under the table
1201 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1202 #' @export
1203 pander.lme <- function(x, caption = attr(x, 'caption'), ...)
1204 pander(summary(x), caption = caption, summary = FALSE, ...)
1205
1206
1207 #' Pander method for describe class
1208 #'
1209 #' Prints a describe object in Pandoc's markdown.
1210 #' @param x an describe object
1211 #' @param caption caption (string) to be shown under the table
1212 #' @param digits number of digits of precision
1213 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1214 #' @export
1215 pander.describe <- function(x, caption = attr(x, 'caption'), digits = panderOptions('digits'), ...) {
1216 if (is.null(caption) & !is.null(storage$caption)) {
1217 caption <- get.caption()
1218 }
1219 if (length(dim(x)) == 1) {
1220 class(x) <- 'list'
1221 attr(x, 'call') <- NULL
1222 pander(x, digits = digits, caption = caption, ...)
1223 } else {
1224 class(x) <- 'data.frame'
1225 pander(x, digits = digits, caption = caption, ...)
1226 }
1227 invisible()
1228 }
1229
1230
1231 #' Pander method for survdiff class
1232 #'
1233 #' Prints an survdiff object in Pandoc's markdown.
1234 #' @param x an survdiff object
1235 #' @param caption caption (string) to be shown under the table
1236 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1237 #' @export
1238 pander.survdiff <- function(x, caption = attr(x, 'caption'), ...) {
1239
1240 if (is.null(caption)) {
1241 if (is.null(storage$caption)) {
1242 caption <- pandoc.formula.return(x$call$formula, text = 'Call:')
1243 } else {
1244 caption <- get.caption()
1245 }
1246 }
1247
1248 if (length(x$n) == 1) {
1249 z <- sign(x$exp - x$obs) * sqrt(x$chisq)
1250 temp <- c(x$obs, x$exp, z, signif(1 - pchisq(x$chisq, 1), panderOptions('digits')))
1251 names(temp) <- c('Observed', 'Expected', 'Z', 'p')
1252 temp <- t(temp)
1253 } else {
1254 if (is.matrix(x$obs)) {
1255 otmp <- apply(x$obs, 1, sum)
1256 etmp <- apply(x$exp, 1, sum)
1257 } else {
1258 otmp <- x$obs
1259 etmp <- x$exp
1260 }
1261 df <- sum(1 * (etmp > 0)) - 1
1262 p <- 1 - pchisq(x$chisq, df[!is.na(df)])
1263 temp <- cbind(x$n, otmp, etmp, (otmp - etmp) ^ 2 / etmp, (otmp - etmp) ^ 2 / diag(x$var))
1264 dimnames(temp) <- list(names(x$n), c('N', 'Observed', 'Expected', '(O-E)^2/E', '(O-E)^2/V'))
1265 caption <- paste(caption, sprintf('Chisq = %f \non %d degrees of freedom, p = %f', x$chisq, df, p), sep = ' ')
1266 }
1267
1268 temp <- as.data.frame(temp, checknames = FALSE)
1269 pandoc.table(temp, caption = caption, ...)
1270
1271 }
1272
1273
1274 #' Pander method for survfit class
1275 #'
1276 #' Prints an survfit object in Pandoc's markdown.
1277 #'
1278 #' @param x the result of a call to the survfit function.
1279 #' @param caption caption (string) to be shown under the table
1280 #' @param scale a numeric value to rescale the survival time, e.g., if the input data to survfit were in days, scale=365 would scale the printout to years.
1281 #' @param print.rmean,rmean options for computation and display of the restricted mean
1282 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1283 #' @export
1284 #' @importFrom utils getFromNamespace
1285 pander.survfit <- function (x, caption = attr(x, 'caption'),
1286 scale = 1, print.rmean = getOption('survfit.print.rmean'),
1287 rmean = getOption('survfit.rmean'), ...) {
1288
1289 if (is.null(caption) & !is.null(storage$caption)) {
1290 caption <- get.caption()
1291 }
1292
1293 omit <- x$na.action
1294
1295 if (length(omit)){
1296 pander(list(naprint(omit)), list.type = 'none')
1297 }
1298
1299 if (!missing(print.rmean) && is.logical(print.rmean) && missing(rmean)) {
1300 rmean <- ifelse(print.rmean, 'common', 'none')
1301 }
1302
1303 if (is.null(rmean)) {
1304 if (is.logical(print.rmean)) {
1305 rmean <- ifelse(print.rmean, 'common', 'none')
1306 } else {
1307 rmean <- 'none'
1308 }
1309 }
1310
1311 if (is.numeric(rmean)) {
1312 if (is.null(x$start.time)) {
1313 if (rmean < min(x$time)) {
1314 stop('Truncation point for the mean is < smallest survival')
1315 }
1316 } else {
1317 if (rmean < x$start.time) {
1318 stop('Truncation point for the mean is < smallest survival')
1319 }
1320 }
1321 } else {
1322 rmean <- match.arg(rmean, c('none', 'common', 'individual'))
1323 if (length(rmean) == 0) {
1324 stop('Invalid value for rmean option')
1325 }
1326 }
1327
1328 temp <- getFromNamespace('survmean', 'survival')(x, scale = scale, rmean)
1329 pandoc.table(temp$matrix, caption = ...)
1330
1331 if (rmean != 'none') {
1332 if (rmean == 'individual') {
1333 pander('* restricted mean with variable upper limit')
1334 } else {
1335 pander(paste('* restricted mean with upper limit = ', format(temp$end.time[1])))
1336 }
1337 }
1338
1339 }
1340
1341 #' Pander method for smooth.spline class
1342 #'
1343 #' Prints an smooth.spline object in Pandoc's markdown.
1344 #' @param x an smooth.spline object
1345 #' @param ... igroned parameters
1346 #' @export
1347 pander.smooth.spline <- function(x, ...) {
1348
1349 x <- as.list(capture.output(x)[-1:-3])
1350 pandoc.list(x, add.end.of.list = FALSE)
1351
1352 }
1353
1354
1355 #' Pander method for rlm class
1356 #'
1357 #' Prints an rlm object in Pandoc's markdown.
1358 #' @param x an rlm object
1359 #' @param caption caption (string) to be shown under the table
1360 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1361 #' @export
1362 pander.rlm <- function(x, caption = attr(x, 'caption'), ...) {
1363
1364 if (is.null(caption)) {
1365 if (is.null(storage$caption)) {
1366 if (!is.null(x$call)) {
1367 caption <- pandoc.formula.return(x$call$formula, text = 'Fitting linear model by robust regression:')
1368 } else {
1369 caption <- 'Fitting linear model by robust regression'
1370 }
1371 } else {
1372 caption <- get.caption()
1373 }
1374 }
1375
1376 if (x$converged) {
1377 cat('Converged in', length(x$conv), 'iterations\n')
1378 } else {
1379 cat('Ran', length(x$conv), 'iterations without convergence\n')
1380 }
1381
1382 coef <- x$coefficients
1383 pandoc.table(coef, caption = caption, ...)
1384 nobs <- length(x$residuals)
1385 rdf <- nobs - length(coef)
1386 cat('Degrees of freedom:', nobs, 'total;', rdf, 'residual\n\n')
1387
1388 if (nzchar(mess <- naprint(x$na.action))) {
1389 cat(' (', mess, ')\n', sep = '')
1390 }
1391
1392 cat('Scale estimate:', format(signif(x$s, 3)), '\n')
1393
1394 }
1395
1396
1397 #' Pander method for stat.table class
1398 #'
1399 #' Prints an stat.table object in Pandoc's markdown.
1400 #' @param x an stat.table object
1401 #' @param caption caption (string) to be shown under the table
1402 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1403 #' @export
1404 pander.stat.table <- function(x, caption = attr(x, 'caption'), ...) {
1405
1406 if (is.null(caption) & !is.null(storage$caption)) {
1407 caption <- get.caption()
1408 }
1409
1410 if (length(dim(x)) == 2) {
1411 pandoc.table(t(x), caption = caption, ...)
1412 return(invisible())
1413 }
1414
1415 if (length(dim(x)) == 3) {
1416
1417 xx <- list()
1418
1419 for (i in 1:dim(x)[2]) {
1420 xx[[i]] <- x[, i, ]
1421 }
1422
1423 xx <- do.call(rbind, xx)
1424 xx <- apply(xx, c(1, 2), format, digits = panderOptions('digits'))
1425 dn <- dimnames(x)
1426 lgroup <- list(names(dn)[2], dn[[2]])
1427 tgroup <- names(dn)[3]
1428 c.s <- length(dn[[3]])
1429 xx <- rbind(colnames(xx), xx)
1430 xx <- cbind(unlist(lgroup), xx)
1431 xx <- rbind(c(rep('', c.s - 1), tgroup, ''), xx)
1432 colnames(xx) <- NULL
1433 pandoc.table(xx, caption = caption, emphasize.rows = c(1, 2), emphasize.cols = 1, ...)
1434 }
1435
1436 }
1437
1438
1439 #' Pander method for sessionInfo class
1440 #'
1441 #' Prints an sessionInfo object in Pandoc's markdown.
1442 #' @param x an sessionInfo object
1443 #' @param locale (defaut:\code{TRUE}) if to print locale output
1444 #' @param compact (defaut:\code{TRUE}) if output shoud be compact (ommiting extra line breaks and spaces, inline printing of lists)
1445 #' @param ... ignored parameters
1446 #' @export
1447 pander.sessionInfo <- function (x, locale = TRUE, compact = TRUE, ...) {
1448
1449 mkLabel <- function(L, n) {
1450 vers <- sapply(L[[n]], function(x) x[['Version']])
1451 pkg <- sapply(L[[n]], function(x) x[['Package']])
1452 sprintf('%s(v.%s)', pkg, vers)
1453 }
1454
1455 cat(pandoc.strong(x$R.version$version.string), '\n\n', sep = '')
1456 cat(pandoc.strong('Platform:'), x$platform, '\n\n', sep = ' ')
1457
1458 if (locale) {
1459 cat(pandoc.strong('locale:'))
1460 cat('\n')
1461 pander(gsub('[/]', '||', strsplit(x$locale, ';', fixed = TRUE)[[1]]), ...)
1462 cat('\n')
1463 }
1464
1465 if (compact) {
1466 attached.base.packages <- pander_return(x$basePkgs, quote = FALSE, ...)
1467 other.attached.packages <- pander_return(mkLabel(x, 'otherPkgs'), quote = FALSE, ...)
1468 load.via.namespaces <- pander_return(mkLabel(x, 'loadedOnly'), quote = FALSE, ...)
1469 } else {
1470 attached.base.packages <- pandoc.list.return(x$basePkgs, add.end.of.list = FALSE, ...)
1471 other.attached.packages <- pandoc.list.return(mkLabel(x, 'otherPkgs'), add.end.of.list = FALSE, ...)
1472 load.via.namespaces <- pandoc.list.return(mkLabel(x, 'loadedOnly'), add.end.of.list = FALSE, ...)
1473 }
1474
1475 cat('\n')
1476 cat(pandoc.strong('attached base packages:'), '\n')
1477 cat(attached.base.packages)
1478
1479 if (!is.null(x$otherPkgs)) {
1480 cat('\n\n')
1481 cat(pandoc.strong('other attached packages:'), '\n')
1482 cat(other.attached.packages)
1483 }
1484
1485 if (!is.null(x$loadedOnly)) {
1486 cat('\n\n')
1487 cat(pandoc.strong('loaded via a namespace (and not attached):'), '\n')
1488 cat(load.via.namespaces)
1489 }
1490
1491 invisible(x)
1492
1493 }
1494
1495
1496 #' Pander method for microbenchmark class
1497 #'
1498 #' Prints an microbenchmark object in Pandoc's markdown.
1499 #' @param x an microbenchmark object
1500 #' @param caption caption (string) to be shown under the table
1501 #' @param expr.labels expression labels that will replace default ones (similar to rownames, which microbenchmark class table does not have)
1502 #' @param unit units in which values should be printed (for example second, microseconds, etc.). Should be one of ns, us, ms, s, t, hz, khz, mhz, eps, f
1503 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1504 #' @export
1505 pander.microbenchmark <- function(x, caption = attr(x, 'caption'), expr.labels, unit, ...) {
1506
1507 xs <- summary(x, unit = unit)
1508
1509 if (is.null(caption)) {
1510 if (is.null(storage$caption)) {
1511 caption <- paste('Unit: ', attr(xs, 'unit'), sep = '')
1512 } else {
1513 caption <- get.caption()
1514 }
1515 }
1516
1517 if (!missing(expr.labels)) {
1518 xs[, 1] <- as.vector(xs[, 1])
1519 xs[1:length(expr.labels), 1] <- expr.labels
1520 }
1521
1522 pander(xs, caption = caption, ...)
1523
1524 }
1525
1526
1527 #' Pander method for function class
1528 #'
1529 #' Prints an function object in Pandoc's markdown.
1530 #' @param x an function object
1531 #' @param add.name (defaut:\code{FALSE}) if to add function name to output or just to print a body
1532 #' @param verbatim (defaut:\code{TRUE}) if to add tabulation, so pandoc conversion will rander it properly
1533 #' @param syntax.highlighting (defaut:\code{FALSE}) if to add hyghlighting tag for R syntax
1534 #' @param ... ignored parameters
1535 #' @export
1536 pander.function <- function(x, add.name = FALSE, verbatim = TRUE, syntax.highlighting = FALSE, ...) {
1537
1538 fname <- substitute(x)
1539 ps <- ''
1540
1541 if (syntax.highlighting) {
1542 cat('```r\n')
1543 } else {
1544 ps <- ifelse(verbatim, '\t', '')
1545 }
1546
1547 if (!is.null(add.name) && add.name) {
1548 cat(ps, fname, ' <- ', sep = '')
1549 }
1550
1551 for (line in deparse(x)) {
1552 cat(ps, line, '\n', sep = '')
1553 }
1554
1555 if (syntax.highlighting) {
1556 cat('```')
1557 }
1558
1559 }
1560
1561
1562 #' Pander method for tabular class
1563 #'
1564 #' Renders an tabular object in Pandoc's markdown.
1565 #' @param x an function object
1566 #' @param caption caption (string) to be shown under the table
1567 #' @param digits number of digits of precision
1568 #' @param emphasize.rownames (defaut:\code{TRUE}) if rownames should be highlighted
1569 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1570 #' @export
1571 pander.tabular <- function(x, caption = attr(x, 'caption'),
1572 emphasize.rownames = TRUE, digits = panderOptions('digits'), ...) {
1573 if (is.null(caption) & !is.null(storage$caption)) {
1574 caption <- get.caption()
1575 }
1576 data <- as.matrix(x, format = T, rowLabels = F, colLabels = F, digits = digits)
1577 rlabels <- attr(x, 'rowLabels')
1578 rlabels[is.na(rlabels)] <- ''
1579 clabels <- attr(x, 'colLabels')
1580 clabels[is.na(clabels)] <- ''
1581 if (!is.null(colnames(rlabels))) {
1582 ## needed for case of more complex tabular structure (see examples)
1583 cl <- colnames(rlabels)
1584 data <- cbind(rlabels, data)
1585 clabels <- cbind(rbind(matrix('',
1586 nrow = (nrow(clabels) - 1),
1587 ncol = length(cl)),
1588 colnames(rlabels)),
1589 clabels)
1590 }
1591 clabels <- apply(clabels, c(2), paste, collapse = '\\ \n')
1592 colnames(data) <- clabels
1593 if (emphasize.rownames) {
1594 pandoc.table(data, caption = caption, keep.line.breaks = TRUE, emphasize.cols = 1:length(cl), ...)
1595 } else {
1596 pandoc.table(data, caption = caption, keep.line.breaks = TRUE, ...)
1597 }
1598 }
1599
1600 #' Pander method for summary.table class
1601 #'
1602 #' Renders an summary.table object in Pandoc's markdown.
1603 #' @param x an function object
1604 #' @param caption caption (string) to be shown under the table
1605 #' @param print.call (defaut:\code{TRUE}) if call should be printed
1606 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1607 #' @export
1608 pander.summary.table <- function(x, caption = attr(x, 'caption'), print.call = T, ...) {
1609 if (is.null(caption)) {
1610 if (!is.null(storage$caption)) {
1611 caption <- get.caption()
1612 } else {
1613 caption <- 'Test for independence of all factors'
1614 }
1615 }
1616 if (!is.null(x$call) && print.call) {
1617 cat('Call: ')
1618 print(x$call)
1619 }
1620 cat('Number of cases in table:', x$n.cases, '\n')
1621 cat('Number of factors:', x$n.vars, '\n')
1622 if (x$n.vars > 1) {
1623 ch <- x$statistic
1624 tdf <- data.frame('Chisq' = ch, 'df' = x$parameter, 'p-value' = x$p.value)
1625 pandoc.table(tdf, caption = caption, ...)
1626 if (!x$approx.ok) {
1627 cat('Chi-squared approximation may be incorrect\n')
1628 }
1629 }
1630 }
1631
1632 #' Pander method for randomForest class
1633 #'
1634 #' Renders an randomForest object in Pandoc's markdown.
1635 #' @param x an randomForest object
1636 #' @param digits number of digits of precision
1637 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1638 #' @export
1639 pander.randomForest <- function (x, digits = panderOptions('digits'), ...) {
1640 cat('\nCall: ', pandoc.formula.return(x$call), '\n')
1641 cat('Type of random forest: ', x$type, '\n', sep = '')
1642 cat('Number of trees: ', x$ntree, '\n', sep = '')
1643 cat('No. of variables tried at each split: ', x$mtry, '\n\n', sep = '')
1644 if (x$type == 'classification') {
1645 if (!is.null(x$confusion)) {
1646 cat('OOB estimate of error rate: ',
1647 round(x$err.rate[x$ntree, 'OOB'] * 100, digits = digits), '%\n', sep = '')
1648 pandoc.table(x$confusion, caption = 'Confusion Matrix', digits = digits, ...)
1649 if (!is.null(x$test$err.rate)) {
1650 cat('Test set error rate: ',
1651 round(x$test$err.rate[x$ntree, 'Test'] * 100, digits = 2),
1652 '%\n',
1653 sep = '')
1654 pandoc.table(x$test$confusion, caption = 'Test Confusion Matrix', digits = digits, ...)
1655 }
1656 }
1657 }
1658 if (x$type == 'regression') {
1659 if (!is.null(x$mse)) {
1660 cat('Mean of squared residuals: ', x$mse[length(x$mse)], '\n', sep = '')
1661 cat('% Var explained: ', round(100 * x$rsq[length(x$rsq)], digits = 2), '\n', sep = '')
1662 if (!is.null(x$test$mse)) {
1663 cat('Test set MSE: ',
1664 round(x$test$mse[length(x$test$mse)], digits = digits),
1665 '\n', sep = '')
1666 cat('% Test Var explained: ',
1667 round(100 * x$test$rsq[length(x$test$rsq)],
1668 digits = 2), '\n', sep = '')
1669 }
1670 }
1671 if (!is.null(x$coefs)) {
1672 cat('Bias correction applied:\n')
1673 cat('Intercept: ', x$coefs[1], '\n')
1674 cat('Slope: ', x$coefs[2], '\n')
1675 }
1676 }
1677 }
1678
1679 #' Prints an irts object from tseries package in Pandoc's markdown.
1680 #' @param x an irts object
1681 #' @param caption caption (string) to be shown under the table
1682 #' @param format string passed to format when printing dates (POSIXct or POSIXt)
1683 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1684 #' @export
1685 pander.irts <- function(x, caption = attr(x, 'caption'), format = panderOptions('date'), ...) {
1686
1687 if (is.null(caption) & !is.null(storage$caption)) {
1688 caption <- get.caption()
1689 }
1690 m <- as.matrix(x$value)
1691 colnames(m) <- NULL
1692 rownames(m) <- format(x$time, format = format)
1693 pander(m, caption = caption, ...)
1694 }
1695
1696 #' Prints an summary.manova object from stats package in Pandoc's markdown.
1697 #' @param x an summary.manova object
1698 #' @param add.significance.stars if significance stars should be shown for P value
1699 #' @param caption caption (string) to be shown under the table
1700 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1701 #' @export
1702 pander.summary.manova <- function (x, caption = attr(x, 'caption'), add.significance.stars = FALSE, ...) {
1703 if (length(stats <- x$stats)) {
1704 pander.anova(stats, caption = caption, add.significance.stars = add.significance.stars, ...)
1705 } else {
1706 cat('No error degrees of freedom\n\n')
1707 pander(data.frame(Df = x$Df, row.names = x$row.names), caption = caption, ...)
1708 }
1709 invisible(x)
1710 }
1711
1712 #' Pander method for manova class
1713 #'
1714 #' Prints an manova object in Pandoc's markdown.
1715 #' @param x an manovv object
1716 #' @param caption caption (string) to be shown under the table
1717 #' @param add.significance.stars if significance stars should be shown for P value
1718 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1719 #' @export
1720 pander.manova <- function(x, caption = attr(x, 'caption'), add.significance.stars = FALSE, ...)
1721 pander(summary(x), caption = caption, add.significance.stars = add.significance.stars, ...)
1722
1723 #' Pander method for gtable class
1724 #'
1725 #' Renders an gtable object in Pandoc's markdown.
1726 #' @param x an gtable object
1727 #' @param zsort Sort by z values? Default \code{FALSE}
1728 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1729 #' @export
1730 pander.gtable <- function(x, zsort = FALSE, ...) {
1731 if (nrow(x$layout) == 0) {
1732 return()
1733 }
1734 pos <- as.data.frame(format(as.matrix(x$layout[c('t', 'r',
1735 'b', 'l')])), stringsAsFactors = FALSE)
1736 grobNames <- vapply(x$grobs, as.character, character(1))
1737 info <- data.frame(z = x$layout$z, cells = paste('(', pos$t, '-', pos$b, ',', pos$l, '-', pos$r, ')', sep = ''),
1738 name = x$layout$name,
1739 grob = grobNames)
1740 if (zsort) {
1741 info <- info[order(x$layout$z), ]
1742 }
1743 pander(info)
1744 }
1745
1746 #' Prints an summary.nls object from stats package in Pandoc's markdown.
1747 #' @param x an summary.nls object
1748 #' @param summary (defaut:\code{TRUE}) if used for summary.lm or lm
1749 #' @param add.significance.stars if significance stars should be shown for P value
1750 #' @param digits number of digits of precision
1751 #' @param show.convergence (defaut:\code{FALSE}) if to print convergence info
1752 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1753 #' @export
1754 pander.summary.nls <- function(x, summary = TRUE, add.significance.stars = FALSE,
1755 digits = panderOptions('digits'), show.convergence = FALSE, ...) {
1756 cat('\n')
1757 pandoc.formula(x$call$formula,
1758 text = 'Fitting nonlinear regression model:',
1759 add.line.breaks = TRUE)
1760
1761 if (summary) {
1762 coef <- x$coefficients
1763 if (add.significance.stars) {
1764 coef[, 4] <- pander::add.significance.stars(coef[, 4])
1765 }
1766 pander(x$coefficients, caption = 'Parameters', ...)
1767 if (add.significance.stars) {
1768 cat('\nSignif. codes: 0 \'***\' 0.001 \'**\' 0.01 \'*\' 0.05 \'.\' 0.1 \' \' 1\n')
1769 }
1770 if (!is.null(x$correlation) && NCOL(x$correlation) > 1) {
1771 pander(x$correlation, caption = 'Correlation of Parameter Estimates', ...)
1772 }
1773 cat('\nResidual standard error:',
1774 format(signif(x$sigma, digits)), 'on', x$df[2L], 'degrees of freedom\n')
1775 } else {
1776 pandoc.table(x$coefficients[, 1], caption = 'Parameter Estimates', digits = digits, ...)
1777 cat('\nresidual sum-of-squares:', format(signif(x$sigma, digits)), '\n')
1778 }
1779
1780 if (show.convergence && !is.null(x$convInfo)) {
1781 if (identical(x$call$algorithm, 'port')) {
1782 cat('\nAlgorithm \'port\', convergence message: ',
1783 x$convInfo$stopMessage, '\n', sep = '')
1784 } else {
1785 cat('\nNumber of iterations', ifelse(x$convInfo$isConv, 'to convergence:', 'till stop:'),
1786 x$convInfo$finIter, '\nAchieved convergence tolerance:',
1787 format(x$convInfo$finTol, digits = digits), '\n')
1788 if (!x$convInfo$isConv) {
1789 cat('Reason stopped:', x$convInfo$stopMessage, '\n')
1790 }
1791 }
1792 }
1793 }
1794
1795 #' Prints an nls object from stats package in Pandoc's markdown.
1796 #' @param x an nls object
1797 #' @param show.convergence (defaut:\code{FALSE}) if to print convergence info
1798 #' @param digits number of digits of precision
1799 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1800 #' @export
1801 pander.nls <- function(x, digits = panderOptions('digits'), show.convergence = FALSE, ...) {
1802 pander.summary.nls(summary(x), summary = FALSE, add.significance.stars = FALSE,
1803 digits = digits, show.convergence = show.convergence, ...)
1804 }
1805
1806 #' Prints an arima object from stats package in Pandoc's markdown.
1807 #' @param x an arima object
1808 #' @param digits number of digits of precision
1809 #' @param se if to include standard error in coefficients table (default \code{TRUE})
1810 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1811 #' @export
1812 pander.Arima <- function(x, digits = panderOptions('digits'), se = TRUE, ...) {
1813 cat('\nCall:', pandoc.formula.return(x$call), '', sep = '\n')
1814 cn <- names(x$coef)
1815 coef <- matrix(x$coef, nrow = 1)
1816 colnames(coef) <- cn
1817 if (se && nrow(x$var.coef)) {
1818 ses <- rep_len(0, length(coef))
1819 ses[x$mask] <- sqrt(diag(x$var.coef))
1820 coef <- rbind(coef, s.e. = ses)
1821 }
1822 pandoc.table(coef, caption = 'Coefficients', digits = digits, ...)
1823 cm <- x$call$method
1824 if (is.null(cm) || cm != 'CSS')
1825 cat('\nsigma^2 estimated as ', format(x$sigma2, digits = digits),
1826 ': log likelihood = ', format(round(x$loglik, 2)),
1827 ', aic = ', format(round(x$aic, 2)), '\n', sep = '')
1828 else cat('\nsigma^2 estimated as ', format(x$sigma2, digits = digits),
1829 ': part log likelihood = ', format(round(x$loglik, 2)),
1830 '\n', sep = '')
1831 invisible(x)
1832 }
1833
1834 #' Prints an polr object from MASS package in Pandoc's markdown.
1835 #' @param x an polr object
1836 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1837 #' @export
1838 pander.polr <- function (x, ...) {
1839 if (!is.null(cl <- x$call)) {
1840 cat('\nCall:', pandoc.formula.return(cl), '', sep = '\n')
1841 }
1842 if (length(coef(x))) {
1843 pandoc.table(coef(x), caption = 'Coefficients', ...)
1844 } else {
1845 cat('\nNo coefficients\n')
1846 }
1847 pandoc.table(x$zeta, caption = 'Intercepts', ...)
1848 cat('\nResidual Deviance:', format(x$deviance, nsmall = 2L), '\n')
1849 cat('AIC:', format(x$deviance + 2 * x$edf, nsmall = 2L), '\n')
1850 if (nzchar(mess <- naprint(x$na.action))) {
1851 cat('(', mess, ')\n', sep = '')
1852 }
1853 if (x$convergence > 0) {
1854 cat('Warning: did not converge as iteration limit reached\n')
1855 }
1856 invisible()
1857 }
1858
1859 #' Prints an ols object from rms package in Pandoc's markdown.
1860 #' @param x an ols object
1861 #' @param long if to print the correlation matrix of parameter estimates. default(\code{FALSE})
1862 #' @param coefs if to the table of model coefficients, standard errors, etc. default(\code{TRUE})
1863 #' @param digits passed to \code{format}. Can be a vector specifying values for each column (has to be the same length as number of columns).
1864 #' @param round passed to \code{round}. Can be a vector specifying values for each column (has to be the same length as number of columns). Values for non-numeric columns will be disregarded.
1865 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1866 #' @export
1867 #' @importFrom stats quantile
1868 pander.ols <- function (x, long = FALSE, coefs = TRUE,
1869 digits = panderOptions('digits'), round = panderOptions('round'), ...) {
1870 requireNamespace('rms', quietly = TRUE)
1871 stats <- x$stats
1872 pen <- length(x$penalty.matrix) > 0
1873 resid <- x$residuals
1874 n <- length(resid)
1875 p <- length(x$coef) - (names(x$coef)[1] == 'Intercept')
1876 if (length(stats) == 0) {
1877 cat('n=', n, ' p=', p, '\n\n', sep = '')
1878 }
1879 ndf <- stats['d.f.']
1880 df <- c(ndf, n - ndf - 1, ndf)
1881 r2 <- stats['R2']
1882 sigma <- stats['Sigma']
1883 rdf <- df[2]
1884 rsqa <- 1 - (1 - r2) * (n - 1) / rdf
1885 lrchisq <- stats['Model L.R.']
1886 ci <- x$clusterInfo
1887 if (lst <- length(stats)) {
1888 misc <- rms::reListclean(Obs = stats['n'], sigma = sigma, d.f. = df[2], `Cluster on` = ci$name, Clusters = ci$n) #nolint
1889 lr <- rms::reListclean(`LR chi2` = lrchisq, d.f. = ndf, `Pr(> chi2)` = 1 - pchisq(lrchisq, ndf)) #nolint
1890 disc <- rms::reListclean(R2 = r2, `R2 adj` = rsqa, g = stats['g']) #nolint
1891 sdf <- multitable(list(misc, lr, disc))
1892 colnames(sdf) <- c('', 'Model Likelihood\nRatio Test', 'Discrimination\nIndexes')
1893 caption <- pandoc.formula.return(x$call$formula, text = 'Fitting linear model:')
1894 pandoc.table(sdf, keep.line.breaks = TRUE, caption = caption, ...)
1895 }
1896 if (rdf > 5) {
1897 if (length(dim(resid)) == 2) {
1898 rq <- apply(t(resid), 1, quantile)
1899 dimnames(rq) <- list(c('Min', '1Q', 'Median', '3Q',
1900 'Max'), dimnames(resid)[[2]])
1901 } else {
1902 rq <- quantile(resid)
1903 names(rq) <- c('Min', '1Q', 'Median', '3Q', 'Max')
1904 }
1905 pandoc.table(rq, caption = 'Residuals', ...)
1906 }
1907 else if (rdf > 0) {
1908 pandoc.table(resid, caption = 'Residuals', ...)
1909 }
1910 if (nsingular <- df[3] - df[1]) {
1911 cat(nsingular, 'coefficients not defined because of singularities', '\n')
1912 }
1913 se <- sqrt(diag(x$var))
1914 if (coefs) {
1915 obj <- list(coef = x$coefficients, se = se, errordf = rdf)
1916 U <- coef_mat(obj, coefs = coefs)
1917 pandoc.table(U, caption = 'Coeficients', ...)
1918 }
1919 if (!pen) {
1920 if (long && p > 0) {
1921 correl <- diag(1 / se) %*% x$var %*% diag(1 / se)
1922 dimnames(correl) <- dimnames(x$var)
1923 ll <- lower.tri(correl)
1924 correl[ll] <- format(round(correl[ll], digits = round), digits = digits, ...)
1925 correl[!ll] <- ''
1926 pandoc.table(correl[-1, - (p + 1), drop = FALSE],
1927 caption = 'Correlation of Coefficients',
1928 digits = digits,
1929 round = round, ...)
1930 }
1931 }
1932 invisible()
1933 }
1934
1935 #' Prints an summary.polr object from MASS package in Pandoc's markdown.
1936 #' @param x an summary.polr object
1937 #' @param digits number of digits of precision passed to format
1938 #' @param round number of rounding digits passed to round
1939 #' @param keep.trailing.zeros to show or remove trailing zeros in numbers on a column basis width
1940 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1941 #' @export
1942 pander.summary.polr <- function(x, digits = panderOptions('digits'), round = panderOptions('round'),
1943 keep.trailing.zeros = panderOptions('keep.trailing.zeros'), ...) {
1944 if (!is.null(cl <- x$call)) {
1945 cat('\nCall:', pandoc.formula.return(cl), '', sep = '\n')
1946 }
1947 pc <- x$pc
1948 if (pc > 0) {
1949 pander(x$coefficients[seq_len(pc), , drop = FALSE], caption = 'Coeficients', #nolint
1950 digits = digits, round = round, keep.trailing.zeros = keep.trailing.zeros, ...)
1951 } else {
1952 cat('\nNo coefficients\n')
1953 }
1954 pander(x$coefficients[ (pc + 1L):nrow(x$coefficients), , drop = FALSE], caption = 'Intercepts', #nolint
1955 digits = digits, round = round, keep.trailing.zeros = keep.trailing.zeros, ...)
1956 cat('\nResidual Deviance:', format(x$deviance, nsmall = 2L), '\n\n')
1957 cat('AIC:', format(x$deviance + 2 * x$edf, nsmall = 2L), '\n\n')
1958 if (nzchar(mess <- naprint(x$na.action))) {
1959 cat('(', mess, ')\n\n', sep = '')
1960 }
1961 if (!is.null(correl <- x$correlation)) {
1962 ll <- lower.tri(correl)
1963 correl <- apply(correl, c(1, 2),
1964 p, wrap = '', digits = digits, round = round, keep.trailing.zeros = keep.trailing.zeros)
1965 correl[!ll] <- ''
1966 pander(correl[-1L, -ncol(correl)],
1967 digits = digits, round = round, keep.trailing.zeros = keep.trailing.zeros,
1968 caption = 'Correlation of Coefficients', ...)
1969 }
1970 invisible(x)
1971 }
1972
1973 #' Prints an survreg object from survival package in Pandoc's markdown.
1974 #' @param x an survreg object
1975 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1976 #' @export
1977 pander.survreg <- function (x, ...) {
1978 pander(summary(x), summary = FALSE, ...)
1979 }
1980
1981 #' Prints an survreg object from survival package in Pandoc's markdown.
1982 #' @param x an survreg object
1983 #' @param summary if summary should be printed
1984 #' @param digits number of digits of precision passed to format
1985 #' @param round number of rounding digits passed to round
1986 #' @param keep.trailing.zeros to show or remove trailing zeros in numbers on a column basis width
1987 #' @param ... optional parameters passed to raw \code{pandoc.table} function
1988 #' @export
1989 pander.summary.survreg <- function(x, summary = TRUE, digits = panderOptions('digits'),
1990 round = panderOptions('round'),
1991 keep.trailing.zeros = panderOptions('keep.trailing.zeros'), ...) {
1992 if (!is.null(cl <- x$call)) {
1993 cat('\nCall:', pandoc.formula.return(cl), '', sep = '\n\n')
1994 }
1995 if (!is.null(x$fail)) {
1996 cat(' Survreg failed.', x$fail, '\n\n')
1997 return(invisible())
1998 }
1999 if (summary) {
2000 pandoc.table(x$table, caption = 'Model statistics',
2001 digits = digits, round = round, keep.trailing.zeros = keep.trailing.zeros, ...)
2002 } else {
2003 coef <- x$coef
2004 if (any(nas <- is.na(coef))) {
2005 if (is.null(names(coef))) {
2006 names(coef) <- paste('b', 1:length(coef), sep = '')
2007 }
2008 cat('\nCoefficients: (', sum(nas), ' not defined because of singularities)\n',
2009 sep = '')
2010 }
2011 pandoc.table(coef, caption = 'Coefficients',
2012 digits = digits, round = round, keep.trailing.zeros = keep.trailing.zeros, ...)
2013
2014 }
2015 if (nrow(x$var) == length(coef)) {
2016 cat('\nScale fixed at', format(x$scale), '\n')
2017 } else if (length(x$scale) == 1) {
2018 cat('\nScale=', format(x$scale), '\n')
2019 } else {
2020 pandoc.table(x$scale, caption = 'Scale', ...)
2021 }
2022 nobs <- length(x$linear)
2023 chi <- 2 * diff(x$loglik)
2024 df <- sum(x$df) - x$idf
2025 pandoc.table(data.frame('Loglik(model)' = x$loglik[2], 'Loglik(intercept only)' = x$loglik[1]), ...)
2026 if (df > 0) {
2027 cat('Chisq=', p(chi, wrap = ''), 'on', p(df, wrap = ''),
2028 'degrees of freedom, p=', p(signif(1 - pchisq(chi, df), 2), wrap = ''), '\n\n')
2029 } else {
2030 cat('\n')
2031 }
2032 if (summary) {
2033 if (x$robust) {
2034 cat('(Loglikelihood assumes independent observations)\n\n')
2035 }
2036 cat('Number of Newton-Raphson Iterations:', p(trunc(x$iter), wrap =), '\n\n') #nolint
2037 }
2038 omit <- x$na.action
2039 if (length(omit)) {
2040 cat('n=', nobs, ' (', naprint(omit), ')\n', sep = '')
2041 } else {
2042 cat('n=', nobs, '\n')
2043 }
2044 if (summary) {
2045 if (!is.null(correl <- x$correlation)) {
2046 p <- dim(correl)[2]
2047 if (p > 1) {
2048 ll <- lower.tri(correl)
2049 correl <- apply(correl, c(1, 2),
2050 p, wrap = '', digits = digits, round = round, keep.trailing.zeros = keep.trailing.zeros)
2051 correl[!ll] <- ''
2052 pander(correl[-1L, -ncol(correl)],
2053 digits = digits, round = round, keep.trailing.zeros = keep.trailing.zeros,
2054 caption = 'Correlation of Coefficients', ...)
2055 }
2056 }
2057 }
2058 invisible()
2059 }
2060
2061 #' Prints an lrm object from rms package in Pandoc's markdown.
2062 #' @param x an lrm object
2063 #' @param coefs if to the table of model coefficients, standard errors, etc. default(\code{TRUE})
2064 #' @param ... optional parameters passed to raw \code{pandoc.table} function
2065 #' @export
2066 pander.lrm <- function (x, coefs = TRUE, ...) {
2067 requireNamespace('rms', quietly = TRUE)
2068 ns <- x$non.slopes
2069 nstrata <- x$nstrata
2070 if (!length(nstrata)) {
2071 nstrata <- 1
2072 }
2073 pm <- x$penalty.matrix
2074 penaltyFactor <- NULL
2075 if (length(pm)) {
2076 psc <- ifelse(length(pm) == 1, sqrt(pm), sqrt(diag(pm)))
2077 penalty.scale <- c(rep(0, ns), psc)
2078 cof <- matrix(x$coef[ - (1:ns)], ncol = 1)
2079 pandoc.table(as.data.frame(x$penalty, row.names = ''), caption = 'Penalty factors', ...)
2080 penaltyFactor <- as.vector(t(cof) %*% pm %*% cof)
2081 }
2082 est.exp <- 1:ns
2083 if (length(x$est)) {
2084 est.exp <- c(est.exp, ns + x$est[x$est + ns <= length(x$coefficients)])
2085 }
2086 vv <- diag(x$var)
2087 cof <- x$coef
2088 stats <- x$stats
2089 maxd <- signif(stats['Max Deriv'], 1)
2090 ci <- x$clusterInfo
2091 misc <- rms::reListclean(Obs = stats['Obs'],
2092 `Sum of weights` = stats['Sum of Weights'],
2093 Strata = if (nstrata > 1) nstrata,
2094 `Cluster on` = ci$name, Clusters = ci$n,
2095 `max |deriv|` = maxd)
2096 if (length(x$freq) < 4) {
2097 names(x$freq) <- paste(' ', names(x$freq), sep = '')
2098 misc <- c(misc[1], x$freq, misc[-1])
2099 }
2100 lr <- rms::reListclean(`LR chi2` = stats['Model L.R.'],
2101 d.f. = stats['d.f.'],
2102 `Pr(> chi2)` = stats['P'],
2103 Penalty = penaltyFactor)
2104 disc <- rms::reListclean(R2 = stats['R2'], g = stats['g'], gr = stats['gr'],
2105 gp = stats['gp'], Brier = stats['Brier'])
2106 discr <- rms::reListclean(C = stats['C'], Dxy = stats['Dxy'], gamma = stats['Gamma'],
2107 `tau-a` = stats['Tau-a'])
2108 sdf <- multitable(list(misc, lr, disc, discr))
2109 colnames(sdf) <- c('', 'Model Likelihood\nRatio Test',
2110 'Discrimination\nIndexes', 'Rank Discrim.\nIndexes')
2111 caption <- pandoc.formula.return(x$call$formula, text = 'Fitting logistic regression model:')
2112 pandoc.table(sdf, keep.line.breaks = TRUE, caption, ...)
2113 if (coefs) {
2114 obj <- list(coef = cof, se = sqrt(vv), aux = if (length(pm)) penalty.scale, auxname = 'Penalty Scale')
2115 U <- coef_mat(obj, coefs = coefs)
2116 pandoc.table(U, caption = 'Coeficients', ...)
2117 }
2118 invisible()
2119 }
2120
2121 #' Prints an orm object from rms package in Pandoc's markdown.
2122 #' @param x an orm object
2123 #' @param coefs if to the table of model coefficients, standard errors, etc. default(\code{TRUE})
2124 #' @param intercepts if to print intercepts, by default, intercepts are only printed if there are fewer than 10 of them
2125 #' @param ... optional parameters passed to raw \code{pandoc.table} function
2126 #' @export
2127 pander.orm <- function (x, coefs = TRUE, intercepts = x$non.slopes < 10, ...) {
2128 requireNamespace('rms', quietly = TRUE)
2129 ns <- x$non.slopes
2130 cik <- attr(x$coef, 'intercepts')
2131 if (length(cik) && intercepts) {
2132 warning('intercepts=TRUE not implemented for fit.mult.impute objects')
2133 intercepts <- FALSE
2134 }
2135 pm <- x$penalty.matrix
2136 penaltyFactor <- NULL
2137 if (length(pm)) {
2138 psc <- ifelse(length(pm) == 1, sqrt(pm), sqrt(diag(pm)))
2139 penalty.scale <- c(rep(0, ns), psc)
2140 cof <- matrix(x$coef[ - (1:ns)], ncol = 1)
2141 pandoc.table(as.data.frame(x$penalty, row.names = ''), caption = 'Penalty factors', ...)
2142 penaltyFactor <- as.vector(t(cof) %*% pm %*% cof)
2143 }
2144 vv <- diag(vcov(x, intercepts = ifelse(intercepts, 'all', 'none')))
2145 if (!intercepts) {
2146 if (!length(cik)) {
2147 nints <- ns
2148 } else if (length(cik) == 1 && cik == 0) {
2149 nints <- 0
2150 } else {
2151 length(cik)
2152 }
2153 ints.to.delete <- vector()
2154 if (ns != 0 && nints != 0) {
2155 ints.to.delete <- 1:nints
2156 }
2157 vv <- c(rep(NA, nints), vv)
2158 }
2159 cof <- x$coef
2160 stats <- x$stats
2161 maxd <- signif(stats['Max Deriv'], 1)
2162 ci <- x$clusterInfo
2163 misc <- rms::reListclean(Obs = stats['Obs'], `Unique Y` = stats['Unique Y'],
2164 `Cluster on` = ci$name, Clusters = ci$n, `Median Y` = stats['Median Y'],
2165 `max |deriv|` = maxd)
2166 if (length(x$freq) < 4) {
2167 names(x$freq) <- paste(' ', names(x$freq), sep = '')
2168 misc <- c(misc[1], x$freq, misc[-1])
2169 }
2170 lr <- rms::reListclean(`LR chi2` = stats['Model L.R.'], #nolint
2171 d.f. = stats['d.f.'],
2172 `Pr(> chi2)` = stats['P'],
2173 `Score chi2` = stats['Score'],
2174 `Pr(> chi2)` = stats['Score P'], Penalty = penaltyFactor)
2175 disc <- rms::reListclean(R2 = stats['R2'], g = stats['g'], gr = stats['gr'], #nolint
2176 `|Pr(Y>=median)-0.5|` = stats['pdm'])
2177 discr <- rms::reListclean(rho = stats['rho']) #nolint
2178 sdf <- multitable(list(misc, lr, disc, discr))
2179 colnames(sdf) <- c('', 'Model Likelihood\nRatio Test',
2180 'Discrimination\nIndexes', 'Rank Discrim.\nIndexes')
2181 caption <- switch(x$family, logistic = 'Logistic (Proportional Odds)',
2182 probit = 'Probit', cauchit = 'Cauchy', loglog = '-log-log',
2183 cloglog = 'Complementary log-log')
2184 caption <- paste(caption, 'Ordinal Regression Model')
2185 caption <- pandoc.formula.return(x$call$formula, text = caption)
2186 pandoc.table(sdf, keep.line.breaks = TRUE, caption, ...)
2187 if (coefs) {
2188 if (!intercepts) {
2189 j <- -ints.to.delete
2190 cof <- cof[j]
2191 vv <- vv[j]
2192 if (length(pm)) {
2193 penalty.scale <- penalty.scale[j]
2194 }
2195 }
2196 obj <- list(coef = cof, se = sqrt(vv), aux = if (length(pm)) penalty.scale, auxname = 'Penalty Scale')
2197 U <- coef_mat(obj, coefs = coefs)
2198 pandoc.table(U, caption = 'Coeficients', ...)
2199 }
2200 invisible()
2201 }
2202
2203 #' Prints an Grm object from rms package in Pandoc's markdown.
2204 #' @param x an Grm object
2205 #' @param coefs if to the table of model coefficients, standard errors, etc. default(\code{TRUE})
2206 #' @param ... optional parameters passed to raw \code{pandoc.table} function
2207 #' @export
2208 #' @importFrom stats coef pchisq vcov
2209 #' @rdname pander.glm.rms
2210 pander.Glm <- function (x, coefs = TRUE, ...) {
2211 requireNamespace('rms', quietly = TRUE)
2212 cof <- coef(x)
2213 lr <- x$null.deviance - x$deviance
2214 dof <- x$rank - (names(cof)[1] == 'Intercept')
2215 pval <- 1 - pchisq(lr, dof)
2216 ci <- x$clusterInfo
2217 misc <- rms::reListclean(Obs = length(x$residuals), `Residual d.f.` = x$df.residual,
2218 `Cluster on` = ci$name, Clusters = ci$n, g = x$g)
2219 lr <- rms::reListclean(`LR chi2` = lr, d.f. = dof, `Pr(> chi2)` = pval) #nolint
2220 sdf <- multitable(list(misc, lr))
2221 colnames(sdf) <- c('', 'Model Likelihood\nRatio Test')
2222 caption <- pandoc.formula.return(x$call$formula, text = 'General Linear Model')
2223 pandoc.table(sdf, keep.line.breaks = TRUE, caption, ...)
2224 if (coefs) {
2225 se <- sqrt(diag(vcov(x)))
2226 obj <- list(coef = cof, se = se)
2227 U <- coef_mat(obj, coefs = coefs)
2228 pandoc.table(U, caption = 'Coeficients', ...)
2229 }
2230 invisible()
2231 }
2232
2233 #' Prints an cph object from rms package in Pandoc's markdown.
2234 #' @param x an cph object
2235 #' @param table if to print event frequency statistics. default(\code{TRUE})
2236 #' @param conf.int set to e.g. .95 to print 0.95 confidence intervals on simple hazard ratios (which are usually meaningless as one-unit changes are seldom relevant and most models contain multiple terms per predictor)
2237 #' @param coefs if to the table of model coefficients, standard errors, etc. default(\code{TRUE})
2238 #' @param ... optional parameters passed to raw \code{pandoc.table} function
2239 #' @export
2240 #' @importFrom stats qnorm
2241 pander.cph <- function (x, table = TRUE, conf.int = FALSE, coefs = TRUE, ...) {
2242 requireNamespace('rms', quietly = TRUE)
2243 if (table && length(x$n) && is.matrix(x$n)) {
2244 pandoc.table(x$n, caption = 'Status', ...)
2245 }
2246 if (length(x$coef)) {
2247 stats <- x$stats
2248 ci <- x$clusterInfo
2249 misc <- rms::reListclean(Obs = stats['Obs'], Events = stats['Events'],
2250 `Cluster on` = ci$name, Clusters = ci$n,
2251 Center = x$center)
2252 lr <- rms::reListclean(`LR chi2` = stats['Model L.R.'], d.f. = stats['d.f.'],
2253 `Pr(> chi2)` = stats['P'], `Score chi2` = stats['Score'],
2254 `Pr(> chi2)` = stats['Score P'])
2255 disc <- rms::reListclean(R2 = stats['R2'], Dxy = stats['Dxy'],
2256 g = stats['g'], gr = stats['gr'])
2257 sdf <- multitable(list(misc, lr, disc))
2258 colnames(sdf) <- c('', 'Model Likelihood\nRatio Test',
2259 'Discrimination\nIndexes')
2260 caption <- pandoc.formula.return(x$call$formula, text = 'Cox Proportional Hazards Model')
2261 pandoc.table(sdf, keep.line.breaks = TRUE, caption, ...)
2262 beta <- x$coef
2263 se <- sqrt(diag(x$var))
2264 if (coefs) {
2265 se <- sqrt(diag(x$var))
2266 obj <- list(coef = x$coef, se = se)
2267 U <- coef_mat(obj, coefs = coefs)
2268 pandoc.table(U, caption = 'Coeficients', ...)
2269 }
2270 if (conf.int) {
2271 zcrit <- qnorm( (1 + conf.int) / 2 )
2272 tmp <- cbind(exp(beta), exp(-beta),
2273 exp(beta - zcrit * se),
2274 exp(beta + zcrit * se))
2275 dimnames(tmp) <- list(names(beta),
2276 c('exp(coef)', 'exp(-coef)',
2277 paste('lower ', p(conf.int, wrap = ''), sep = ''),
2278 paste('upper ', p(conf.int, wrap = ''), sep = '')))
2279 pandoc.table(tmp, caption = 'Confidence interval', ...)
2280 }
2281 }
2282 invisible()
2283 }
2284
2285 #' Prints an summary.rms from rms package in Pandoc's markdown.
2286 #' @param x an summary.rms object
2287 #' @param ... optional parameters passed to raw \code{pandoc.table} function
2288 #' @export
2289 pander.summary.rms <- function (x, ...) {
2290 cstats <- dimnames(x)[[1]]
2291 for (i in 1:7) cstats <- cbind(cstats, signif(x[, i], 5))
2292 dimnames(cstats) <- list(rep('', nrow(cstats)), c('Factor', dimnames(x)[[2]][1:7]))
2293 pandoc.table(cstats, ...)
2294 if ( (A <- attr(x, 'adjust')) != '')
2295 cat('\nAdjusted to:', A, '\n')
2296 blab <- switch(attr(x, 'conf.type'),
2297 `bootstrap nonparametric percentile` = 'Bootstrap nonparametric percentile confidence intervals',
2298 `bootstrap BCa` = 'Bootstrap BCa confidence intervals',
2299 `basic bootstrap` = 'Basic bootstrap confidence intervals',
2300 '')
2301 if (blab != '') {
2302 cat('\n', blab, '\n', sep = '')
2303 }
2304 cat('\n')
2305 invisible()
2306 }
2307
2308 #' Prints an ets object from forecast package in Pandoc's markdown.
2309 #' @param x an ets object
2310 #' @param digits number of digits of precision
2311 #' @param ... optional parameters passed to raw \code{pandoc.table} function
2312 #' @export
2313 pander.ets <- function(x, digits = panderOptions('digits'), ...) {
2314 cat('\nCall:', pandoc.formula.return(x$call), '', sep = '\n')
2315 cat('Type of ets: ', x$method, '\n', sep = '')
2316 lambda <- x$lambda
2317 isn <- names(x$initstate)
2318 initstate <- matrix(x$initstate, nrow = 1)
2319 colnames(initstate) <- isn
2320 sp <- x$par['alpha']
2321 if (x$components[2] != 'N'){
2322 sp <- c(sp, x$par['beta'])
2323 }
2324 if (x$components[3] != 'N'){
2325 sp <- c(sp, x$par['gamma'])
2326 }
2327 if (x$components[4] != 'FALSE'){
2328 sp <- c(sp, x$par['phi'])
2329 }
2330 if (!is.null(lambda)){
2331 cat('\nBox-Cox transformation: lambda =', round(lambda, panderOptions('digits')), '\n')
2332 }
2333 pandoc.table(sp, caption = 'Smoothing parameters', digits = digits, ...)
2334 pandoc.table(initstate, caption = 'Initial states', digits = digits, ...)
2335 cat('\nsigma^2 estimated as', format(x$sigma2, digits = digits))
2336 if (!is.null(x$loglik)){
2337 cat(': log likelihood = ', format(round(x$loglik, 2)))
2338 }
2339 if (!is.null(x$aic)){
2340 cat(', aic = ', format(round(x$aic, 2)), '\n', sep = '')
2341 }
2342 invisible(x)
2343 }