Jesper.Lindberg
Jesper.Lindberg

Reputation: 339

Wrap long text output in R markdown

I'm doing a report in R markdown and executing a code that is giving me an error. I want to show this error in the report, so I set error=TRUE so I can knit the document anyway.

However, the error can't fint on one line and is not split into several lines when I knit the document. Resulting in the fact that I can't see the desired error.

Things I've done to try solving this:

tidy.opts=list(width.cutoff=60),tidy=TRUE

https://github.com/yihui/knitr-examples/blob/master/077-wrap-output.Rmd

The method I use to get the error: B<-solve(A,b) The actual error:

Error in solve.default(A, b) : system is computationally singular: reciprocal condition number = 7.13971e-17

Upvotes: 1

Views: 2841

Answers (1)

Martin Schmelzer
Martin Schmelzer

Reputation: 23889

Maybe this solves your problem already:

There are different output hooks. If you alter the example you posted a little bit by changing the error hook instead of the output hook, it works:

error_hook <- knitr::knit_hooks$get("error")
knitr::knit_hooks$set(error = function(x, options) {
  if (!is.null(n <- options$linewidth)) {
    x = knitr:::split_lines(x)
    if (any(nchar(x) > n)) x = strwrap(x, width = n)
    x = paste(x, collapse = '\n')
  }
  error_hook(x, options)
})

MWE:

---
title: "example"
date: "22 January 2019"
output: pdf_document
---

```{r}
error_hook <- knitr::knit_hooks$get("error")
knitr::knit_hooks$set(error = function(x, options) {
  if (!is.null(n <- options$linewidth)) {
    x = knitr:::split_lines(x)
    if (any(nchar(x) > n)) x = strwrap(x, width = n)
    x = paste(x, collapse = '\n')
  }
  error_hook(x, options)
})
```

```{r, linewidth = 10, error = T}
print(iDoNotExist)
```

enter image description here

Upvotes: 3

Related Questions