在Knitr输出中对长字符串进行文本包装(RStudio) [英] Textwrapping long string in knitr output (RStudio)
问题描述
我有一个很长的向量字符串(DNA序列),最多要成千上万个连续字符,我想添加到我的knitr报告输出中. RStudio可以在控制台中完美地处理文本换行,但是当我生成knitr html输出时,我只能看到一行文本,并且它仅在页面上运行.
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输出
针织输出
有什么方法可以调整编织输出以包装文本?
Any way of adjusting knitr output to wrap text?
谢谢.
推荐答案
我建议您尝试 R Markdown v2 .默认的HTML模板会为您自动换行.这是通过HTML标签pre
/code
的CSS定义来实现的,例如word-wrap: break-word; word-break: break-all;
.这些定义实际上来自Bootstrap(当前 rmarkdown 使用 Bootstrap 2.3 .2 ).
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).
您仍在使用R Markdown的第一个版本,即 markdown 包.当然,您可以使用一些自定义CSS定义来达到相同的目标,而这只需要您了解有关HTML/CSS的更多信息.
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.
另一种解决方案是使用我在下面编写的函数str_break()
手动中断长字符串:
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')
```
这篇关于在Knitr输出中对长字符串进行文本包装(RStudio)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!