Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide printing statement in RMarkdown

Tags:

r

r-markdown

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.

like image 766
needRhelp Avatar asked Oct 09 '17 18:10

needRhelp


People also ask

How do I hide the output in R markdown?

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.

How do I hide code but show output in R markdown?

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.

How do I show output in Rmarkdown?

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 .


1 Answers

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.

like image 73
alistaire Avatar answered Sep 28 '22 11:09

alistaire