Loop in R markdown
Could that be what you want?
---
title: "Untitled"
author: "Author"
output: html_document
---
```{r, results='asis'}
for (i in 1:2){
cat('\n')
cat("#This is a heading for ", i, "\n")
hist(cars[,i])
cat('\n')
}
```
This answer was more or less stolen from here.
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")
}
```
Creating R Markdown htmls by looping
The link you mention gives all the elements to generate a parametrized report.
On your example, you could knit with custom parameters using rmarkdown::render
.
markdown file : test.Rmd
---
title: "Create markdown htmls with loop"
author: "Nathan Roe"
date: "2/17/2022"
output: html_document
params:
letter: 'a'
---
# `r paste('Processing letter ',letter)`
```{r}
letter
```
html
file generation with loop :
for (letter in letters[1:5] ) {
rmarkdown::render(input = 'test.Rmd',
output_file = paste0(letter,".html"),
params = list(letter = letter))
}
...
how to use a for loop in rmarkdown?
You can use the asis
option:
---
title: "Untitled"
output: ioslides_presentation
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(dplyr)
# needed so r will include javascript/css dependencies needed for striped tables:
kable(cars, "html") %>% kable_styling(bootstrap_options = "striped")
```
```{r, results = "asis"}
for (threshold in c(20, 25)) {
cat("\n\n##\n\n")
x <- cars %>%
filter(dist < threshold) %>%
kable('html') %>%
kable_styling(bootstrap_options = "striped")
cat(x)
}
```
Output two questions from a loop in one page-r markdown
I had to remove spaces from your code, but this works. I commented out some of the vertical space. Because of the page size this automatically set two per page. (Although, I did add \newpage
in R Markdown before the chunk so the title and all that wouldn't be on the same page as the forms.
If you wanted to enforce the next page, you can use the if
statement commented out at the end to add \\newpage
to every other form. (It's checking to see if i
is even or odd by looking for a modulo AKA remainder.)
\newpage
```{r echo=F, comment=NA, results='asis'}
for (i in 1:nrow(D2)){
a = D2%>% select(Prob) %>% slice(i) %>% pull
cat(" \n")
cat("\\vspace{1cm}") # removed
cat(i,".",a)
cat(" \n")
# cat("\\vspace{1cm}")
cat("\\begin{Form}
\\TextField[width = 16cm,%
height = 6cm,%. # I reduced here by 1, as well
multiline=true,%
value = {%
Please show your work here
}%
]{}
\\end{Form}")
cat(" \n")
# cat("\\vspace{7cm}") # removed
cat(" \n")
cat("\\begin{Form}
\\TextField[width = 16cm,%
height = 3cm,%
multiline=true,%
value = {%
Please write your answer here
}%
]{}
\\end{Form}")
# if((i %% 2) == 0) cat("\\newpage ")
}
```
Generate tables in a loop with tab.id with officedown R package
You can probably set these values in a loop by using knitr::opts_chunk$set()
. I would probably prefer set_caption
in your case.
To print flextables in a loop inside an R Markdown document, use flextable_to_rmd()
. See Looping in R Mardown documents.
---
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r}
library(flextable)
library(officer)
library(officedown)
library(magrittr)
dfs <- list(
df1 = head(iris),
df2 = head(mtcars)
)
df_ids <- names(dfs)
```
```{r results='asis'}
for(i in df_ids){
z <- flextable(dfs[[i]]) %>%
set_caption(caption = paste("Result for item", i),
style = "Table Caption",
autonum = run_autonum(seq_id = "tab", bkm = i))
flextable_to_rmd(z)
crossref_id <- sprintf("\\@ref(tab:%s)", i)
cat("\n\n\nA ref to table ", crossref_id, "\n\n\n\n")
}
```
R Markdown, output test results in loop
Solution Type 1
You could do a capture.output(cat(.))
approach with some lapply
-looping. Send the output to a file and use rmarkdown::render(.)
.
This is the R code producing a *.pdf
.
capture.output(cat("---
title: 'Test Results'
author: 'Tom & co.'
date: '11 10 2019'
output: pdf_document
---\n\n```{r setup, include=FALSE}\n
knitr::opts_chunk$set(echo = TRUE)\n
mtcars <- data.frame(mtcars)\n```\n"), file="_RMD/Tom.Rmd") # here of course your own data
lapply(seq(mtcars), function(i)
capture.output(cat("# Model", i, "\n\n```{r chunk", i, ", comment='', echo=FALSE}\n\
print(summary(lm(mpg ~ ", names(mtcars)[i] ,", mtcars)))\n```\n"),
file="_RMD/Tom.Rmd", append=TRUE))
rmarkdown::render("_RMD/Tom.Rmd")
Produces:
Solution Type 2
When we want to automate the output of multiple model summaries in the rmarkdown itself, we could chose between 1. selecting chunk option results='asis'
which would produce code output but e.g. # Model 1
headlines, or 2. to choose not to select it, which would produce Model 1 but destroys the code formatting. The solution is to use the option and combine it with inline code that we can paste()
together with another sapply()
-loop within the sapply()
for the models.
In the main sapply
we apply @G.Grothendieck's venerable solution to nicely substitute the Call:
line of the output using do.call("lm", list(.))
. We need to wrap an invisible(.)
around it to avoid the unnecessary sapply()
output [[1]] [[2]]...
of the empty lists produced.
I included a ". "
into the cat()
, because leading white space like ` this`
will be rendered to this
in lines 6 and 10 of the summary outputs.
This is the rmarkdown script producing a *pdf
that can also be executed ordinary line by line:
---
title: "Test results"
author: "Tom & co."
date: "15 10 2019"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Overview
This is an example of an ordinary code block with output that had to be included.
```{r mtcars, fig.width=3, fig.height=3}
head(mtcars)
```
# Test results in detail
The test results follow fully automated in detail.
```{r mtcars2, echo=FALSE, message=FALSE, results="asis"}
invisible(sapply(tail(seq(mtcars), -2), function(i) {
fo <- reformulate(names(mtcars)[i], response="mpg")
s <- summary(do.call("lm", list(fo, quote(mtcars))))
cat("\n## Model", i - 2, "\n")
sapply(1:19, function(j)
cat(paste0("`", ". ", capture.output(s)[j]), "` \n"))
cat(" \n")
}))
```
***Note:*** This is a concluding remark to show that we still can do other stuff afterwards.
Produces:
(Note: Site 3 omitted)
how to create a loop that includes both a code chunk and text with knitr in R
You can embed the markdown inside the loop using cat()
.
Note: you will need to set results="asis"
for the text to be rendered as markdown.
Note well: you will need two spaces in front of the \n
new line character to get knitr to properly render the markdown in the presence of a plot out.
# Monthly Air Quality Graphs
```{r pressure,fig.width=6,echo=FALSE,message=FALSE,results="asis"}
attach(airquality)
for(i in unique(Month)) {
cat(" \n###", month.name[i], "Air Quaility \n")
#print(plot(airquality[airquality$Month == i,]))
plot(airquality[airquality$Month == i,])
cat(" \n")
}
```
Related Topics
How to Insert (Add) a Row to a SQLite Db Table Using Dplyr Package
Hide Certain Columns in a Responsive Data Table Using Dt Package
Using 'Rvest' to Extract Links
R: How to Draw a Line with Multiple Arrows in It
How to Remove Na from Facet_Wrap in Ggplot2
R - Customizing X Axis Values in Histogram
How to Rotate Legend Symbols in Ggplot2
Geom_Col Is Assigning the Wrong Independent Variable
Using R's Lm on a Dataframe with a List of Predictors
How to Create Base R Plot 'Type = B' Equivalent in Ggplot2
How to Remove Columns with Same Value in R
Subsetting a Data.Frame Given Some Criteria
How to Remove Rows That Have Only 1 Combination for a Given Id