Skip to content

Instantly share code, notes, and snippets.

@thiagomata
Last active February 3, 2019 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagomata/85d53a1f8079be983558f3da9268f2ce to your computer and use it in GitHub Desktop.
Save thiagomata/85d53a1f8079be983558f3da9268f2ce to your computer and use it in GitHub Desktop.
Printing Properly the Output of Functions on R Markdown
# What is this?
Many R functions have a nice printable version that is accessible throw the print function.
But, when we want to get this content and using it to print inside of the HTML or PDF document, the result is not good.
This function helps to get the printable content into a varible.
## The Function
```{r tidy_print_function}
library(stringr)
tidyPrint <- function(data) {
content <- paste0(data,collapse = "\n\n")
content <- str_replace_all(content,"\\t"," ")
content <- str_replace_all(content,"\\ ","\\\\ ")
content <- str_replace_all(content,"\\$","\\\\$")
content <- str_replace_all(content,"\\*","\\\\*")
content <- str_replace_all(content,":",": ")
return(paste("<code>",content,"</code>\n"))
}
```
## Default Print - Inside of a Box
```{r example_of_problem_default,echo=FALSE,include=FALSE}
# Code will be inside of a box
knitr::opts_chunk$set(comment = NA)
t.test(mtcars$mpg,mtcars$wt)
```
... create a box with the result of the print function ...
## Asis Print - Evaluates the Markdown Special Chars
```{r example_of_problem_asis,echo=FALSE,include=TRUE,results='asis'}
# Using results=asis remove the box but evaluates the markdown
# content inside of th string
#
# this may looks good on the RStudio but become a single line with some unexpected
# formatting on the PDF or HTML
knitr::opts_chunk$set(comment = NA)
t.test(mtcars$mpg,mtcars$wt)
```
... funny result, single line and with special formatting ...
## Example of the Solution - No Box and No Special Chars Confusion
```{r my_pre_example,echo=FALSE,include=TRUE,results='asis'}
# This seems kind of ugly in the RStudio but is formatted and
# readable on HTML and PDF output
knitr::opts_chunk$set(comment = NA)
resultTTest <- capture.output(t.test(mtcars$mpg,mtcars$wt))
cat(tidyPrint(resultTTest))
```
... output is fine, no box and no special chars, on HTML and PDF ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment