RMarkdown 文件中 R 代码块输出的宽度被编织到 html

Width of R code chunk output in RMarkdown files knitr-ed to html

问题:

在 html 文件中设置 r 代码输出宽度的当前工作解决方案是什么?我想将宽度设置为大一些,并在 html 输出中使用滑块。

options(width = XXX) 好像不行了。

示例:

---
title: "Width test"
output:
  html_document:
    theme: default
---
```{r global_options, echo = FALSE, include = FALSE}
options(width = 999)
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE,
                      cache = FALSE, tidy = FALSE, size = "small")
```
```{r}
sessionInfo()
```
```{r}
dataM <- matrix(rnorm(100, 5, 2), ncol = 15)
dataM
```

结果:

上面截图中的sessionInfo()输出。

相关:

options(width = 999) 不适合我)

knitr: How to prevent text wrapping in output?

How to adjust the output width of RStudio Markdown output (to HTML)

您可以使用自定义 CSS 重置 widthmax-width,例如像这样:

---
title: "Width test"
output:
  html_document:
    theme: default
---
<style>
.main-container { width: 1200px; max-width:2800px;}
</style>

```{r global_options, echo = FALSE, include = FALSE}
options(width = 999)
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE,
                      cache = FALSE, tidy = FALSE, size = "small")

```{r}
sessionInfo()
```
```{r}
dataM <- matrix(rnorm(100, 5, 2), ncol = 15)
dataM
```

您可以使用它使 pre 块在溢出时水平滚动。

---
title: "Width test"
output:
  html_document:
    theme: default
---

<style>
pre {
  overflow-x: auto;
}
pre code {
  word-wrap: normal;
  white-space: pre;
}
</style>

```{r global_options, echo = FALSE, include = FALSE}
options(width = 999)
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE,
                      cache = FALSE, tidy = FALSE, size = "small")
```
```{r}
sessionInfo()
```
```{r}
dataM <- matrix(rnorm(100, 5, 2), ncol = 20)
dataM
```


对于可滚动高度,创建一个具有最大高度和 overflow-y: auto;overflow-y: scroll;

的容器 div

---
title: "Height test"
output:
  html_document:
    theme: default
---

<style>
.pre-scrolly {
  max-height: 150px;
  overflow-y: auto;
}
</style>

<div class='pre-scrolly'>
```{r}
sessionInfo()
```
</div>

我 运行 遇到了类似的问题,但使用的是 Stata 引擎(更多信息 here)。在这种情况下,事实证明这不是 knitr 本身的问题,而是我的 Stata 设置的问题。

诀窍是在设置线宽的初始设置块之后添加 Stata 特定块

```{r setup_knitr, echo=FALSE, message=FALSE}
# This is the usual setup block needed to set up the Stata Engine
require(knitr)
statapath <- "C:/Program Files (x86)/Stata13/Stata-64.exe"
opts_chunk$set(engine="stata", engine.path=statapath, comment="")
``` 

```{r setup_stata, echo=FALSE,message=FALSE,collectcode=TRUE}
* Now that Stata engine is set up, this block sets up Stata options
set linesize 200
set more off
```