Textwrapping long string in knitr output (RStudio)

有些话、适合烂在心里 提交于 2019-11-30 20:03:57

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')
```
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!