R Knitr Markdown: Output Plots Within for Loop

R knitr Markdown: Output Plots within For Loop

Wrap the qplot in print.

knitr will do that for you if the qplot is outside a loop, but (at least the version I have installed) doesn't detect this inside the loop (which is consistent with the behaviour of the R command line).

R markdown: Use for loop to generate text and display figure/table

You can use result = 'asis' inside the r chunk and use cat() to create the sections.

---
title: "R Notebook"
output:
html_document
---

## Example

```{r, results='asis'}
require(ggplot2)
for(i in 1:5){
cat("### Section ", i, "\n")

df <- mtcars[sample(5),]
tb <- knitr::kable(df, caption = paste0("Table",i))
g1 <- ggplot2::ggplot(df, aes(x = mpg, y = disp, fill = gear)) +
ggplot2::geom_point() +
ggplot2::labs(title = paste0("Figure ", i))
cat("\n")
print(g1)
print(tb)
cat("\n")
}
```

Print ggplot2 and lm objects in a loop in RMarkdown

It looks like this is a case for a template document and knitr::knit_expand(). A canonical answer is here. Working with strings sent me to this answer, as well, since I wasn't entire sure how the "{{" notation worked in this approach.

This approach involves making a template R markdown document in the same directory. Depending on whether you want to include code chunks or need chunk names, that could look something like:

## {{species}}

```{r species_loop-{{species}}, echo = FALSE}
df_filtered <- df %>%
dplyr::filter(Species == "{{species}}")

df_filtered %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()

my_model <- lm(Sepal.Length ~ Petal.Length, data = df_filtered)
summary(my_model)
```

Then your master document code could look like:

```{r}
library(dplyr)
library(ggplot2)

df <- datasets::iris %>%
dplyr::as_tibble()
```

```{r, include = FALSE}
src <- lapply(c("setosa", "versicolor", "virginica"),
function(species) {
knitr::knit_expand(file = "template.Rmd")
}
)
```

`r knitr::knit(text = unlist(src))`

R Markdown: plots within a loop going out of margin when typesetting to PDF

The problem is that the generated .tex file has no spaces between the \includegraphics{} calls. LaTeX gives warnings about overfull hboxes, because the graphics aren't big enough to sit alone on a line, and are too big when it puts two on each line.

You can tell LaTeX (TeX really) to output the bad lines without putting two figures on each line by adding

\pretolerance=10000

in the text before the code chunk. You'll probably want to set it back to its default value

\pretolerance=100

after the code chunk, or LaTeX won't try hyphenation afterwards, and text can look really ugly.

Another way to fix this would be to force each figure to be in its own paragraph. You can do this by adding this code

my_plot_hook <- function(x, options)
paste("\n", knitr::hook_plot_tex(x, options), "\n")
knitr::knit_hooks$set(plot = my_plot_hook)

into a code chunk before you do your plotting. This puts a blank line
before and after each figure.

R Markdown, creating plots in for loop in different div-tags

I found that following solves the issues:

```{r plot_cashflows, results='asis', echo = FALSE}
for( i in 1:10 ){
cat("<div class=\"superbigimage\">")
for( j in 1:10 ){
print(
plot(...)
)
}
cat("</div> \n\n")
}

'```


Related Topics



Leave a reply



Submit