如何显示代码,但隐藏在 RMarkdown 的输出?

我希望我的 html 文件显示代码,而不是这个块的输出:

```{r echo=True, include=FALSE}
fun <- function(b)
{
for(a in b)
{print(a)
return(a * a)}
}
y <- fun(b)
```

当我运行代码,我需要打印看到的进展(这是一个相当长的功能在现实中)。

但是在 knyr 文件中,我在另一个块中使用了输出,所以我不希望在这个块中看到它(而且没有进度的概念,因为代码已经运行过了)。

这里的 echo=True, include=FALSE不起作用: 整个事情是隐藏的(这是 include=FALSE的正常行为)。

我可以用什么参数来隐藏指纹,但显示我的代码?

165999 次浏览

As @ J_F answered in the comments, using {r echo = T, results = 'hide'}.

I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!

You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.

Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
results = "hide")
```

Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.

```{r analysis, results="markup"}
# code here
```

To hide warnings, you can also do {r, warning=FALSE}

```{r eval=FALSE}

The document will display the code by default but will prevent the code block from being executed, and thus will also not display any results.

For muting library("name_of_library") codes, meanly just showing the codes, {r loadlib, echo=T, results='hide', message=F, warning=F} is great. And imho a better way than library(package, warn.conflicts=F, quietly=T)

The results = 'hide' option doesn't prevent other messages to be printed. To hide them, the following options are useful:

  • {r, error=FALSE}
  • {r, warning=FALSE}
  • {r, message=FALSE}

In every case, the corresponding warning, error or message will be printed to the console instead.

For completely silencing the output, here what works for me

```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({




# Your code here
2 * 2
# etc etc




})})
```

The 5 measures used above are

  1. error = FALSE
  2. warning = FALSE
  3. message = FALSE
  4. invisible()
  5. capture.output()