简体   繁体   English

在knitr输出中文本包裹长字符串(RStudio)

[英]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. 我有一个长的矢量字符串(DNA序列),我想要添加到我的knitr报告输出中的几千个连续字符。 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在控制台中完美地处理文本包装,但是当我生成knitr html输出时,我只能看到一行文本,它只是在页面上运行。

RStudio output RStudio输出

knitr output 编织输出

Any way of adjusting knitr output to wrap text? 任何调整knitr输出以包装文本的方法?

Thanks. 谢谢。

I recommend you to try the R Markdown v2 . 我建议你试试R Markdown v2 The default HTML template does text wrapping for you. 默认的HTML模板为您进行文本换行。 This is achieved by the CSS definitions for the HTML tags pre / code , eg word-wrap: break-word; word-break: break-all; 这是通过HTML标签pre / code的CSS定义实现的,例如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 ). 这些定义实际上来自Bootstrap(目前rmarkdown使用Bootstrap 2.3.2 )。

You were still using the first version of R Markdown, namely the markdown package. 你还在使用R Markdown的第一个版本,即降价包。 You can certainly achieve the same goal using some custom CSS definitions, and it just requires you to learn more about HTML/CSS. 您当然可以使用一些自定义CSS定义来实现相同的目标,它只需要您了解有关HTML / CSS的更多信息。

Another solution is to manually break the long string using the function str_break() I wrote below: 另一个解决方案是使用我在下面写的函数str_break()手动中断长字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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