## 11.7 Hide code, text output, messages, or plots

By default, knitr displays all possible output from a code chunk, including the source code, text output, messages, warnings, and plots. You can hide them individually using the corresponding chunk options.

Hide source code:

{r, echo=FALSE}
1 + 1


Hide text output (you can also use results = FALSE):

{r, results='hide'}
print("You will not see the text output.")


Hide messages:

{r, message=FALSE}
message("You will not see the message.")


Hide warning messages:

{r, warning=FALSE}
# this will generate a warning but it will be suppressed
1:2 + 1:3


Hide plots:

{r, fig.show='hide'}
plot(cars)


Note that the plot will be generated in the above chunk. It is
just not displayed in the output.

One frequently asked question about knitr is how to hide package loading messages. For example, when you library(tidyverse) or library(ggplot2), you may see some loading messages. Such messages can also be suppressed by the chunk option message = FALSE.

You can also selectively show or hide these elements by indexing them. In the following example, we only show the fourth and fifth expressions of the R source code (note that a comment counts as one expression), the first two messages, and the second and third warnings:

{r, echo=c(4, 5), message=c(1, 2), warning=2:3}
# one way to generate random N(0, 1) numbers
x <- qnorm(runif(10))
# but we can just use rnorm() in practice
x <- rnorm(10)
x

for (i in 1:5) message('Here is the message ', i)

for (i in 1:5) warning('Here is the warning ', i)


You can use negative indices, too. For example, echo = -2 means to exclude the second expression of the source code in the output.

Similarly, you can choose which plots to show or hide by using indices for the fig.keep option. For example, fig.keep = 1:2 means to keep the first two plots. There are a few shortcuts for this option: fig.keep = "first" will only keep the first plot, fig.keep = "last" only keeps the last plot, and fig.keep = "none" discards all plots. Note that the two options fig.keep = "none" and fig.show = "hide" are different: the latter will generate plots but only hide them, and the former will not generate plot files at all.

For source code blocks in the html_document output, if you do not want to completely omit them (echo = FALSE), you may see Section 7.5 for how to fold them on the page, and allow users to unfold them by clicking the unfolding buttons.