How to show code but hide output in RMarkdown? - r

I want my html file to show the code, but not the output of this chunk:
```{r echo=True, include=FALSE}
fun <- function(b)
{
for(a in b)
{print(a)
return(a * a)}
}
y <- fun(b)
```
When I run the code, i need the print to see the progress (it is quite a long function in reality).
But in the knitr file, I use the output in a further chunk, so I do not want to see it in this one (and there's no notion of progress, since the code has already been run).
This echo=True, include=FALSE here does not work: the whole thing is hidden (which is the normal behavior of include=FALSE).
What are the parameters I could use to hide the prints, but show my code?

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
```

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.

```{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)

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
error = FALSE
warning = FALSE
message = FALSE
invisible()
capture.output()

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

Related

Display Block of R Code in Knitr With Evaluation Turned Off

I am writing a document with fairly resource intensive R code. I want to prevent execution of one block of R code in knitr which is giving me document timeout error in Overleaf.
In R studio, this can be done using eval = FALSE. I want to recreate this in knitr. So far, the only way I have found is to suppress errors using <<setup, include=FALSE, cache=FALSE>>= muffleError <- function(x,options) {} but it only works on the entire document.
I specifically want to prevent evaluation but show the R code.
Is this what you want to do, or have I misunderstood? The eval = FALSE is in one code chunk and the second chunk still plots.
---
title: "A Test Knit"
output: html_document
---
## Show code but don't run
```{r, eval = FALSE}
summary(cars)
```
## Run and render plot
```{r}
plot(pressure)
```

R Markdown citation broken by fig.align and other chunk options

I'm writing a document in R Markdown and use a Bibtex library for my citations. They work fine when I use them in the text, but give me trouble when I try to implement them in a figure caption.
The Bibtex reference is:
#book{TEST,
title = {R for Data Science},
author = {Test Person},
year = {2018},
}
How it works:
```{r carplot, echo=F, warning=F, fig.cap="This is a Test [#TEST]"}
plot(cars)
```
Ouput:
How it gets broken:
```{r carplot, echo=F, warning=F, fig.cap="This is a Test [#TEST]", fig.align="right"}
plot(cars)
```
Output:
I've tried other code chunk options like out.width=".7\\textwidth" and out.extra = 'trim = {0 1.1cm 0 0}, clip' which both cause the citation to break as well. Chunk options like echo=F and warning=F don't seem to be a problem though.
Any Ideas how i can put figure options in the code chunk options whithout it breaking my citation?
I have found a working solution for my problem, even though I still don't unterstand how it was caused in the first place. But for anybody looking for a workaround in the future, here is how I managed to do it:
(ref:CAP1) This is a Test [#TEST]
```{r carplot, echo=F, warning=F, fig.cap="(ref:CAP1)", fig.align="right"}
plot(cars)
```
Like this, the fig.align="right" does not seem to be a problem anymore.

How to suppress dev.off() messages in knitr chunk options with markdown in R

I have a chunk of code I don't want to split up in my .rmd file that I'm knitting in RStudio.
My global options are:
{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, autodep = T, message = FALSE, warnings = FALSE, cache=TRUE, messages=FALSE)
Even my chunk option is:
{r section025, message=FALSE, warning=FALSE}
code here
And the PDF output shows the following in the middle of the page where I have saved an image out in my code:
## pdf
## 2
I seem to have used all the suppression options, so I cannot figure out why this still appears. Thoughts appreciated.
send the result of dev.off() to a garbage variable
whatever <- dev.off()
I got a similar problem. My solution was to use dev.off within invisible()

Graphics on next slide with ioslides using Rstudio's Rmd

I want to have my graph output display on the next slide while the code chunk stays on the first. I am using the default ioslides in Rstudio. I would think that it would be some attribute of the code chunk but I can't figure out what it is.
---
output: ioslides_presentation
---
## Slide with Plot
```{r, echo=TRUE}
plot(cars)
```
Any one have any idea on how to do this in Rstudio?
I want to use this for educational purposes. First showing the code and than revealing the graph. Now I am stuck with doing double code chunks with echo=FALSE and TRUE and eval=FALSE and TRUE.
It's easier to run the code twice, once not evaluating the code, the second time not showing the code.
---
title: "Plot Separation"
output: ioslides_presentation
---
## Plot 1
```{r, eval = FALSE}
plot(1:10)
```
## Plot 2
```{r, echo = FALSE}
plot(1:10)
```
It also avoids the error when smaller is true.
To move a plot to the next slide, you need to add a horizontal rule ---- before it (see documentation). You can modify the default plot hook to do it:
```{r setup, include=FALSE}
library(knitr)
local({
hook_plot = knit_hooks$get('plot')
knit_hooks$set(plot = function(x, options) {
paste0('\n\n----\n\n', hook_plot(x, options))
})
})
```
If you want all your plots to appear on the next slide Yihui's answer is the way to go. But if you want some plots to appear on the same slide you may be better off doing it manually, similar to what you are already doing (and what Dario suggested). Except that I would strongly recommend the use of chunk references. That way you avoid the need to duplicate the code.
---
title: "Plot Separation"
output: ioslides_presentation
---
## Plot code
```{r cars_plot, echo = TRUE, eval = FALSE}
plot(cars)
```
## Plot display
```{r cars_plot, echo = FALSE, eval = TRUE}
```
```
I agree this would be desirable, but I'm finding ioslides to be buggy. Ioslides project started eith google, but was let go a while ago.
You may have better luck with beamer/home slides. But does require a LaTeX distribution to be installed.

R knitr: Possible to programmatically modify chunk labels?

I'm trying to use knitr to generate a report that performs the same set of analyses on different subsets of a data set. The project contains two Rmd files: the first file is a master document that sets up the workspace and the document, the second file only contains chunks that perform the analyses and generates associated figures.
What I would like to do is knit the master file, which would then call the second file for each data subset and include the results in a single document. Below is a simple example.
Master document:
# My report
```{r}
library(iterators)
data(mtcars)
```
```{r create-iterator}
cyl.i <- iter(unique(mtcars$cyl))
```
## Generate report for each level of cylinder variable
```{r cyl4-report, child='analysis-template.Rmd'}
```
```{r cyl6-report, child='analysis-template.Rmd'}
```
```{r cyl8-report, child='analysis-template.Rmd'}
```
analysis-template.Rmd:
```{r, results='asis'}
cur.cyl <- nextElem(cyl.i)
cat("###", cur.cyl)
```
```{r mpg-histogram}
hist(mtcars$mpg[mtcars$cyl == cur.cyl], main = paste(cur.cyl, "cylinders"))
```
```{r weight-histogam}
hist(mtcars$wt[mtcars$cyl == cur.cyl], main = paste(cur.cyl, "cylinders"))
```
The problem is knitr does not allow for non-unique chunk labels, so knitting fails when analysis-template.Rmd is called the second time. This problem could be avoided by leaving the chunks unnamed since unique labels would then be automatically generated. This isn't ideal, however, because I'd like to use the chunk labels to create informative filenames for the exported plots.
A potential solution would be using a simple function that appends the current cylinder to the chunk label:
```r{paste('cur-label', cyl, sep = "-")}
```
But it doesn't appear that knitr will evaluate an expression in the chunk label position.
I also tried using a custom chunk hook that modified the current chunk's label:
knit_hooks$set(cyl.suffix = function(before, options, envir) {
if (before) options$label <- "new-label"
})
But changing the chunk label didn't affect the filenames for generated plots, so I didn't think knitr was utilizing the new label.
Any ideas on how to change chunk labels so the same child document can be called multiple times? Or perhaps an alternative strategy to accomplish this?
For anyone else who comes across this post, I wanted to point out that #Yihui has provided a formal solution to this question in knitr 1.0 with the introduction of the knit_expand() function. It works great and has really simplified my workflow.
For example, the following will process the template script below for every level of mtcars$cyl, each time replacing all instances of {{ncyl}} (in the template) with its current value:
# My report
```{r}
data(mtcars)
cyl.levels <- unique(mtcars$cyl)
```
## Generate report for each level of cylinder variable
```{r, include=FALSE}
src <- lapply(cyl.levels, function(ncyl) knit_expand(file = "template.Rmd"))
```
`r knit(text = unlist(src))`
Template:
```{r, results='asis'}
cat("### {{ncyl}} cylinders")
```
```{r mpg-histogram-{{ncyl}}cyl}
hist(mtcars$mpg[mtcars$cyl == {{ncyl}}],
main = paste({{ncyl}}, "cylinders"))
```
```{r weight-histogam-{{ncyl}}cyl}
hist(mtcars$wt[mtcars$cyl == {{ncyl}}],
main = paste({{ncyl}}, "cylinders"))
```
If you make all chunks in your ** nameless, i.e. ```{r} it works. This, of course, is not very elegant, but there are two issues preventing you from changing the label of the current chunk:
A file is parsed before the code blocks are executed. The parser already detects duplicate labels, before any code is executed or custom hooks are called.
The chunk options (inc. the label) are processed before the hook is called (logical: it's an option that triggers a hook), so the hook cannot change the label anymore.
The fact that unnamed blocks work is that internally they get the label unnamed-chunk-+chunk number.
Blocks cannot have duplicate names as internally knitr references them by label. A fix could be to make knitr add the chunk number to all chunks with duplicate names. Or to reference them by chunk number instead of label, but that seems to me a much bigger change.
There is a similar question posed here I was able to programmatically create r chunks and knit the outputs for use in a flexdashboard (quite useful) based on an arbitrary list of input plots using the knit_expand(text=) and r paste(knitr::knit(text = paste(out, collapse = '\n'))) methods.

Resources