Textwrapping long string in knitr output (RStudio)

后端 未结 1 1139
太阳男子
太阳男子 2021-01-02 08:36

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 wrappin

1条回答
  •  孤城傲影
    2021-01-02 09:10

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

    0 讨论(0)
提交回复
热议问题