Split code into several syntactically invalid chunks in R Knitr - r

Is it possible to get a nonformated markdown text inside a code chunk? My goal is to diplay a description inside a for cycle. In the example below, such operation leads to splitting the code into two syntactically invalid chunks:
I am using for cycle here
```{r results='hide'}
for(i in 1:5){
foo()
```
There is a lot of interesting stuff inside
```{r results='hide'}
bar()
}
```
which would ideally generate:
I am using for cycle here
for(i in 1:5){
foo()
There is a lot of interesting stuff inside
bar()
}

Following advice from the comment by user2706569, you can define the code chunk once with a name and evaluate it. Then you can reuse the code chunk, but only echo the lines you want, and without evaluation.
Drawn from Yihui's examples...
The plots from the original evaluation are
shown, but the code is not echoed here. (To
omit all of the outputs, check out the
chunk options such as `include=FALSE`.)
```{r mychunk, echo=FALSE}
## 'ugly' code that I do not want to show
par(mar = c(4, 4, 0.1, 0.1), cex.lab = 0.95, cex.axis = 0.9,
mgp = c(2, 0.7, 0), tcl = -0.3)
plot(mtcars[, 1:2])
plot(mtcars[, 4:5])
```
Now describe the code as you wish without evaluation.
Here's the first and second lines from the original chunk.
```{r mychunk, echo=1:2, eval=FALSE}
```
Here's the third line.
```{r mychunk, echo=3, eval=FALSE}
```
Here's the fourth line.
```{r mychunk, echo=4, eval=FALSE}
```
Here's the fifth line.
```{r mychunk, echo=5, eval=FALSE}
```

Related

rmarkdown/purrr: remove list indices between plots

When I knit a document containing multiple plots obtained through purrr:map function, I get text slides in between each plot slide containing unwanted list index information (see image slides 2, 4, and 6). I'd like to remove these and just have plots.
I've tried results = "hide" and results = FALSE in the header.
These just return one plot instead of many, AND the text is still
there.
I've tried adding invisible() around my code as recommended
here. I don't see a difference.
How can I remove these and just have three slides with the three plots with no text?
---
title: "Reprex"
output: powerpoint_presentation
---
```{r include=FALSE}
library(tidyverse)
```
```{r echo=FALSE, results = FALSE}
ys <- c("mpg","cyl","disp")
ys %>% map(function(y)
invisible(ggplot(mtcars, aes(hp)) + geom_point(aes_string(y=y))))
```
Try this:
To suppress the console output use purrr::walk instead of map. See e.g. https://chrisbeeley.net/?p=1198
To get each plot printed on a separate slide use results='asis' and add two newlines via cat('\n\n') after each plot.
---
title: "Reprex"
output: powerpoint_presentation
---
```{r include=FALSE}
library(tidyverse)
```
```{r echo=FALSE, results='asis'}
ys <- c("mpg","cyl","disp")
walk(ys, function(y) {
p <- ggplot(mtcars, aes(hp)) + geom_point(aes_string(y=y))
print(p)
cat('\n\n')
})
```

How do I parameterize template blocks in knitr?

Say I have the following code in knitr. How can I run it multiple times with different values of i?
```{r, echo=FALSE}
i<-0.1
```
### X,Y plot of Y=X+e where e is a standard normal distro: mean=0, sd=`r i`
```{r, echo=FALSE}
r<-rnorm(100,mean=0,sd=i)
x<-seq(0,1,length.out=100)
y<-x+r
plot(x,y)
```
EDIT:
As has been suggested ... I tried to do something like this: start a loop in an R code block, have a template in between and then close the loop -- R throws and error.
```{r, echo=FALSE}
for (i in 1:4) {
```
# bla
```{r, echo=FALSE}
}
```
What makes this question tricky is that not only the chunk content (the plot) must be repeated, but the heading as well. That's why we can neither simply reuse the chunk nor just loop over the plot command like
for (i in 1:3) { plot(rnorm(100, sd = i)) }
But it's almost that simple: We loop over the code that produces the plot and output the heading from inside the loop. This requires the chunk option results="asis" and cat to get verbatim markdown output:
```{r, echo=FALSE, results = "asis"}
sdVec <- c(0.1, 0.2, 0.3)
for (sd in sdVec) {
cat(sprintf("\n### X,Y plot of Y=X+e where e ~ N(0, %s)", sd))
r<-rnorm(100,mean=0,sd=sd)
x<-seq(0,1,length.out=100)
y<-x+r
plot(x,y)
}
```
See this answer for related issues.

Figure captions with multiple plots in one chunk

I label my figures like this.
---
title: "xxx"
output:
pdf_document:
fig_caption: true
---
And then in each chunk
```{r, fig.cap="some caption"}
qplot(1:5)
```
This works quite nicely. However in chunks where I plot multiple figures within a loop I can't specify a caption. This produces no caption at all:
```{r, fig.cap="another caption"}
qplot(1:5)
qplot(6:10)
```
How can I specify a figure that counts from the same number as the first chunk for each plot?
You can use a fig.cap argument of length 2 (or the size of your loop):
```{r, fig.cap=c("another caption", "and yet an other")}
qplot(1:5)
qplot(6:10)
```
Found an easy way to dynamically produce plots and add them to the pdf with individual captions, using knitr::fig_chunk as described here. This is also a workaround for OPs comment that message=false (or echo=False or results='asis' for that matter) supresses the fig.cap argument.
```{r my-plots, dev='png', fig.show='hide', echo=FALSE}
# generate plots first
qplot(1:5)
qplot(6:10)
```
```{r, echo=FALSE, results='asis'}
# then put them in the document with the captions
cat(paste0("![some caption](", fig_chunk(label = "my-plots", ext = "png", number = 1), ")\n\n"))
cat(paste0("![another caption](", fig_chunk(label = "my-plots", ext = "png", number = 2), ")\n\n"))
```
Hopefully this helps someone who stumbles upon this question in the future.

Evaluate inline r code in rmarkdown figure caption

I am using RStudio and knitr to knit .Rmd to .docx
I would like to include inline code in figure captions e.g. something like the following in the chunk options:
fig.cap = "Graph of nrow(data) data points"
However, knitr does not evaluate this code, instead just printing the unevaluated command.
Is there a way to get knitr to evaluate r code in figure/table captions?
knitr evaluates chunk options as R code. Therefore, to include a variable value in a figure caption, just compose the required string using paste or sprintf:
fig.cap = paste("Graph of", nrow(data), "data points")
Note that this might be problematic if data is created inside this chunk (and not in a previous chunk) because by default chunk options are evaluated before the chunk itself is evaluated.
To solve this issue, use the package option eval.after to have the option fig.cap be evaluated after the chunk itself has been evaluated:
library(knitr)
opts_knit$set(eval.after = "fig.cap")
Here a complete example:
---
title: "SO"
output:
word_document:
fig_caption: yes
---
```{r fig.cap = paste("Graph of", nrow(iris), "data points.")}
plot(iris)
```
```{r setup}
library(knitr)
opts_knit$set(eval.after = "fig.cap")
```
```{r fig.cap = paste("Graph of", nrow(data2), "data points.")}
data2 <- data.frame(1:10)
plot(data2)
```
The first figure caption works even without eval.after because the iris dataset is always available (as long as datasets has been attached). Generating the second figure caption would fail without eval.after because data2 does not exist before the last chunk has been evaluated.

How to avoid figure filenames in child calls

I would like to reuse a child file from my parent Rmd after modifying my data. The code seems to work fine, but the first figures are stepped over and all figures are replaced by the last one.
Is there a way to force new filenames with each new call?
This is my Parent.Rmd
XParent
========
```{r Opts, echo=FALSE}
opts_chunk$set(fig.show='asis', fig.keep='all', fig.width=3, fig.height=4, options(digits = 2), dev='jpeg')
```
```{r XLoad}
read_chunk(lines = readLines('XCode.R'))
```
```{r ParentChunk}
```
First child call
---------------
#### NOTICE the data is OK but the figure corresponds to the second child call (Y axis = 1200)
```{r CallChild, child='XChild.Rmd'}
```
#### I now modify the dataframe
```{r}
df$dist <- df$dist * 10
```
Second child call
-----------------
As this is the last case, the figure agrees with the data:
```{r CallChild2, child='XChild.Rmd'}
```
This Child.Rmd
XChild
```{r CodeAndFigs}
```
and XCode.R
## #knitr ParentChunk
df <- cars
colMeans(df)
# Y axis' upper limit is 120
plot(cars)
## #knitr CodeAndFigs
colMeans(df)
plot(df)
The figure in the first child call has been replace by the second figure. I have tried playing with different fig.keep and fig.show options with no luck.
With the latest development version on Github (which will turn into knitr 1.3 very soon on CRAN), you can use the fig.path option to specify different figure paths for the child document in two parent chunks CallChild and CallChild2, e.g.
XParent
========
```{r Opts, echo=FALSE}
opts_chunk$set(fig.show='asis', fig.keep='all', fig.width=3, fig.height=4, options(digits = 2), dev='jpeg')
```
```{r XLoad}
read_chunk(lines = readLines('XCode.R'))
```
```{r ParentChunk}
```
First child call
---------------
#### NOTICE the data is OK but the figure corresponds to the second child call (Y axis = 1200)
```{r CallChild, child='XChild.Rmd', fig.path='figure/child-'}
```
#### I now modify the dataframe
```{r}
df$dist <- df$dist * 10
```
Second child call
-----------------
As this is the last case, the figure agrees with the data:
```{r CallChild2, child='XChild.Rmd', fig.path='figure/child2-'}
```
The child document will inherit options from its parent chunk, so the figure paths will no clash if the parent options are different.

Resources