隐藏在 Rmarkdown/knit 中的 R 代码,只显示结果

在我的 R Markdown 文档中,有时候我只是想生成一个不显示实际代码的报告(特别是当我把它发送给我的老板时)。如何隐藏 R 代码并只显示图形和结果?

例如:

---
output: html_document
---


```{r fig.width=16, fig.height=6}
plot(cars)
```

这显示了命令和绘图。如何从 HTML 报告中删除命令?

152080 次浏览

Sure, just do

```{r someVar, echo=FALSE}
someVariable
```

to show some (previously computed) variable someVariable. Or run code that prints etc pp.

So for plotting, I have eg

### Impact of choice of ....
```{r somePlot, echo=FALSE}
plotResults(Res, Grid, "some text", "some more text")
```

where the plotting function plotResults is from a local package.

Might also be interesting for you to know that you can use:

{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)

to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

Just aggregating the answers and expanding on the basics. Here are three options:

1) Hide Code (individual chunk)

We can include echo=FALSE in the chunk header:

```{r echo=FALSE}
plot(cars)
```

2) Hide Chunks (globally).

We can change the default behaviour of knitr using the knitr::opts_chunk$set function. We call this at the start of the document and include include=FALSE in the chunk header to suppress any output:

---
output: html_document
---


```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```


```{r}
plot(cars)
```

3) Collapsed Code Chunks

For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.

---
output:
html_document:
code_folding: "hide"
---




```{r}
plot(cars)
```

enter image description here