10

I have a long vector string (DNA sequence) of up to a couple of thousand sequential characters that I want to add to my knitr report output. RStudio handles the text wrapping perfectly in the console but when I generate the knitr html output I can see only one line of text and it just runs off the page.

RStudio output

knitr output

Any way of adjusting knitr output to wrap text?

Thanks.

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
biomiha
  • 1,358
  • 2
  • 12
  • 25

1 Answers1

8

I recommend you to try the R Markdown v2. The default HTML template does text wrapping for you. This is achieved by the CSS definitions for the HTML tags pre/code, e.g. word-wrap: break-word; word-break: break-all;. These definitions are actually from Bootstrap (currently rmarkdown uses Bootstrap 2.3.2).

You were still using the first version of R Markdown, namely the markdown package. You can certainly achieve the same goal using some custom CSS definitions, and it just requires you to learn more about HTML/CSS.

Another solution is to manually break the long string using the function str_break() I wrote below:

A helper function `str_break()`:

```{r setup}
str_break = function(x, width = 80L) {
  n = nchar(x)
  if (n <= width) return(x)
  n1 = seq(1L, n, by = width)
  n2 = seq(width, n, by = width)
  if (n %% width != 0) n2 = c(n2, n)
  substring(x, n1, n2)
}
```

See if it works:

```{r test}
x = paste(sample(c('A', 'C', 'T', 'G'), 1000, replace = TRUE), collapse = '')
str_break(x)
cat(str_break(x), sep = '\n')
```
Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • The strwrap() function for some reason doesn't work for me, the string still runs off the screen. So far the best way for me has been to use the CSS def "overflow-wrap: break-word", but how do you insert line breaks between multiple strings? e.g.
    ```{r, echo=FALSE, eval=TRUE, tidy=FALSE, strip.white=FALSE} paste(sample(c("A","C","T","G"),1000,replace=T),collapse="") paste(sample(c("A","C","T","G"),1000,replace=T),collapse="") ```
    – biomiha Jun 07 '14 at 17:24
  • @biomiha strwrap() does not work in your case because there are no spaces in the string, so it does not know how to break the string properly. I'll give you an alternative function. The easiest solution is what I said first: use rmarkdown (http://rmarkdown.rstudio.com). If you really want to mess with CSS, that is fine, but you need to learn more about the markdown package, and how to customize the template, and so on (https://support.rstudio.com/hc/en-us/articles/200552186-Customizing-Markdown-Rendering), which might take you a few hours if you do not mind. – Yihui Xie Jun 07 '14 at 18:24
  • Yup, the str_break function is perfect. Thanks Yihui. – biomiha Jun 08 '14 at 08:24