Complete Guide to Showing Code but Hiding Output in RMarkdown

Nov 27, 2025 · Programming · 9 views · 7.8

Keywords: RMarkdown | knitr | code_display_control | output_hiding | chunk_options

Abstract: This article provides a comprehensive exploration of controlling code and output display in RMarkdown documents through knitr chunk options. It focuses on using the results='hide' option to conceal text output while preserving code display, and extends the discussion to other relevant options like message=FALSE and warning=FALSE. The article also offers practical techniques for setting global defaults and overriding individual chunks, enabling flexible document output customization.

Introduction

RMarkdown, as a widely used document generation tool in data science, is highly valued for its powerful code execution and result presentation capabilities. However, in practical usage, we often need precise control over how code and output are displayed in documents. For instance, during debugging we may need to monitor execution progress, but in the final document we want to hide intermediate outputs. This article systematically explains how to achieve this through knitr's chunk options.

Core Problem and Solution

A common scenario RMarkdown users encounter is the need to monitor progress through print statements during code execution, while wanting to display only the code without output in the generated HTML document. Using the traditional include=FALSE option in such cases would hide the entire chunk (both code and output), failing to meet the requirement.

The correct solution is to use the results='hide' option. This option specifically controls the display of text output. When set to 'hide', text output generated by code execution is concealed, while the source code remains visible in the document. Here's a concrete example:

```{r echo=TRUE, results='hide'}
fun <- function(b) {
    for(a in b) {
        print(a)
        return(a * a)
    }
}
y <- fun(b)
```

In this example, although the function uses print statements to track execution progress, these print outputs won't appear in the final HTML document due to results='hide', while the code itself remains clearly visible.

Other Related Output Control Options

Beyond text output, knitr provides various options to control other types of output display:

The following code example demonstrates how to use these options together:

```{r echo=TRUE, results='hide', message=FALSE, warning=FALSE}
library(ggplot2)
# Code here produces output but it's hidden
data <- rnorm(100)
print(summary(data))
```

Global Option Setting and Individual Overrides

To enhance workflow efficiency, we can set global default chunk options. Use the following code in the document's first chunk:

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

With this setup, all subsequent chunks in the document will by default show code but hide text output. If a specific chunk requires different behavior, you can set options individually to override global defaults:

```{r special-chunk, results="markup"}
# This chunk will display text output
important_result <- compute_something()
print(important_result)
```

Advanced Techniques for Selective Display

knitr also supports more granular output control through indexing to selectively show or hide specific elements. For example:

```{r, echo=c(2,3), message=c(1,2)}
# First expression (comment)
x <- 1:10  # Second expression
mean_x <- mean(x)  # Third expression
# Only second and third expressions will display
for(i in 1:3) message('Message ', i)  # Only first two messages will display
```

This selective display capability is particularly valuable when dealing with complex code blocks, allowing precise control over what appears in the document.

Practical Application Recommendations

In practical work, users are advised to fully utilize the resources provided by RStudio to master all available chunk options. Detailed information can be obtained through:

These resources comprehensively list all available chunk options and their usage, serving as invaluable references for daily work.

Conclusion

By appropriately using the various chunk options provided by knitr, users can precisely control how code and output are displayed in RMarkdown documents. The results='hide' option is the ideal solution for the specific need of showing code while hiding output, and when combined with other relevant options, can address various complex document generation requirements. Mastering these techniques will significantly enhance the quality and professionalism of RMarkdown documents.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.