Is there a way to hide printing statements in RMarkdown? I have written a function, which prints progress about the learning behavior of an algorithm to the R console. Here is an example:
f <- function() {
print("Some printing")
return(1)
}
In RMarkdown I have
```{r, eval = TRUE, results = "show"}
res = f()
print(res)
```
This adds "Some printing" and 1 into the RMarkdown output file. Is there a way to suppress "Some printing", but keep the output of the function (here 1)? For warnings, errors and messages there are options, but I could find none for print statements.
You use results="hide" to hide the results/output (but here the code would still be displayed). You use include=FALSE to have the chunk evaluated, but neither the code nor its output displayed.
include = FALSE prevents code and results from appearing in the finished file. R Markdown still runs the code in the chunk, and the results can be used by other chunks. echo = FALSE prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.
If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .
If you use message
in your function instead of print
, you can suppress the message
```{r}
f <- function() {
message("Some printing") # change this line
return(1)
}
res <- f()
print(res) # original prints both
```
#> Some printing
#> [1] 1
either explicitly with suppressMessages
:
```{r}
res <- suppressMessages(f())
print(res)
```
#> [1] 1
or via the message=FALSE
chunk option:
```{r, message=FALSE}
res <- f()
print(res)
```
#> [1] 1
Messages designed for this kind of use. If you really want to keep print
, you could subset (which is awkward), or use capture.output
to capture and store the message while storing the result in another variable:
```{r}
f <- function() {
print("Some printing")
return(1)
}
trash <- capture.output(res <- f())
print(res)
```
#> [1] 1
...but that's still pretty awkward.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With