简体   繁体   中英

Textwrapping long string in knitr output (RStudio)

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.

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 , eg word-wrap: break-word; word-break: break-all; 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')
```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM