rknitrrstudioword-wrapr-markdown

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?


Solution

  • 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')
    ```