I would like to automatically generate R markdown chunks and headings within a for
loop in R for a list
of data.frame
s which varies length depending on input. These are then the input for plot generation. This R markdown document will then be knitted to a html_document
using the package knitr
.
I have attempted the solutions from several similar SO questions which can get me close, but is not what I actually need:
The problem is that I have 4 chunks that I'd like to repeat where each chunk has to have different chunk options (fig.width
, fig.height
) to correctly display the ggplot2
objects in them. So, I can't simply just supply a single set of options in the code chunk itself).
Here is an example of one of my failed attempts (NOTE: the second code block below also contains a comment indicating the chunk options which is required):
# Chunk data demo
data_list <- list(a=data.frame(), b=data.frame(), c=data.frame())
plot_1 <- list()
plot_2 <- list()
for (i in 1:length(data_list)) {
data_list[[i]] <- data.frame(x = 1:5, y = 1:5)
plot_1[[i]] <- ggplot(data_list[[i]], aes(x, y)) + geom_point()
plot_2[[i]] <- ggplot(data_list[[i]], aes(x, y)) + geom_point()
}
#```{r, results='asis'} (Start of R markdown chunk)
# Chunk generation (only 2 chunks are written for brevity)
for (i in 1:length(data_list)) {
# Section heading
cat("\n\n")
cat("##", names(data_list)[i])
# Chunk 1 ----
cat("\n\n")
cat("### Sub-section 1")
cat("\n\n")
cat("**Title 1**")
cat("\n\n")
cat('```{r, fig.width=10, fig.height=10}')
cat("\n\n")
print(plot_1[[i]])
cat("\n\n")
cat('```')
# Chunk 2 ----
cat("\n\n")
cat("### Sub-section 2")
cat("\n\n")
cat("**Title 2**")
cat("\n\n")
cat('```{r, fig.width=10, fig.height=3}') # NOTE: Change in option
cat("\n\n")
print(plot_2[[i]])
cat("\n\n")
cat('```')
cat("\n\n")
}
#``` (End of R markdown chunk)
EDIT: Removed the ggsave()
calls, as not necessary to illustrate the problem which is apparent in the knitted document.