R markdown to PDF - print console output

I work in RStudio for the course, and I want to write my reports using R markdown. I would like to display a specific console output in pdf, which will be the report, in particular the output summary(model), where model, for example. linear model obtained using the command lm. By default, it seems that the console output after converting to pdf with knitr is displayed as-is and with the “#” characters in front of it, which is both ugly for me and also rather cumbersome to solve the problem when setting up the final version of the report.

Is there a better way to display console output, especially when converting my laptops to pdf? Ideally, I would like something like a box surrounding the output (HTML conversion seems to give you exactly that), and it is optimal to be able to add a title to indicate what the result represents. And most of all, no annoying "#" - characters in each line.

I tried searching here and googling for a solution, but I did not find anything that solves my problem.

+4
source share
3 answers

Here is a workaround. The idea is to convert the console output to text that you can create and customize as you wish.

---
title: "Untitled"
output:
  pdf_document: default
---

```{r, echo = F}
print_output <- function(output, cex = 0.7) {
  tmp <- capture.output(output)
  plot.new()
  text(0, 1, paste(tmp, collapse='\n'), adj = c(0,1), family = 'mono', cex = cex)
  box()
}
```

```{r, warning = F}
lm <- lm(mpg ~ hp, data = mtcars)

print_output(summary(lm))
```

which gives: enter image description here

+4
source

, knitr hooks. LaTeX .

TOC:

  • framed.
  • fancyvrb

1. framed.

---
title: "Output Hook"
output: pdf_document
---

```{r setup, include = F}
library(knitr)
opts_chunk$set(comment=NA)
def_hook <- knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
  out <- def_hook(x, options)
  return(paste("\\begin{framed}\\begin{verbatim}", x, "\\end{verbatim}\\end{framed}", collapse = "\n"))
})
```

```{r}
lm(mpg ~ hp, data = mtcars)
```

enter image description here

2. fancyvrb

fancyvrb (. ):

---
title: "Output Hook"
output: pdf_document
header-includes:
  - \DefineVerbatimEnvironment{myVerb}{Verbatim}{numbers=left,numbersep=1mm,frame=lines,framerule=0.4mm,rulecolor=\color{blue}}
---

```{r setup, include = F}
library(knitr)
opts_chunk$set(comment=NA)
def_hook <- knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
  out <- def_hook(x, options)
  return(paste("\\begin{myVerb}\n", x, "\\end{myVerb}", collapse = "\n"))
})
```

```{r}
lm(mpg ~ hp, data = mtcars)
```

enter image description here

+3

Getting rid of ## is the display option in rmarkdown, which is comment = ""for any snippet or opts_chunk$set(comment=NA) in your first code snippet for the entire document.

You should also look at the pander package for a nice print of the outputs.

+2
source

Source: https://habr.com/ru/post/1695937/


All Articles