I will show here two options through an example. The example will be a data frame with two columns. For each row of the column, I will create a Rmd
that will make the sum of the two columns.
Option 1: a script R
and a script Rmd
You will have a script R
principal who will do the analysis and will call the clerk Rmd
in a loop. The script Rmd
then have the different variables that will be defined in the script R
.
Script R
:
# definir dados
df <- data.frame(a = rnorm(10), b = rnorm(10))
for(i in 1:nrow(df))
{
rmarkdown::render('doc.Rmd', output_file = paste0('doc_linha_', i, '.pdf'))
}
Script Rmd
:
---
output: pdf_document
---
A média da linha `r i` do data frame `df` é:
```{r,echo=FALSE}
mean(as.numeric(df[i, ]))
```
How we render the document Rmd
in the same Environment that we define the data frame df
, no problem. Another option is the argument params
of function rmarkdown::render()
Option 2: only one script R
This option is interesting when we need the text to be as flexible as the code. In the following example we will add the name of the line present in the data frame as part of the text in the markdown document:
# definir dados
df <- data.frame(a = rnorm(10), b = rnorm(10), names = paste('Linha', LETTERS[1:10]))
# Para cada loop
# 1. criamos um documento markdown
# 2. renderizamos o documento em pdf
for(i in 1:nrow(df))
{
# criar documento rmarkdown
File = paste0('---
title: Título para ', df[i, 'names'], '
output: pdf_document
---
A média da ', print(df[i, 'names']), ' do data frame `df` é:
```{r,echo=FALSE}
mean(as.numeric(df[i, ]))
```
')
# salvar documento
writeLines(File, 'doc.Rmd')
# renderizar documento
rmarkdown::render('doc.Rmd', output_file = paste0('doc_linha_', i, '.pdf'))
}
# deletar documento temporário
file.remove('doc.Rmd')
Hello! Can you provide us some code you have tried and better exemplify what you want to do?
– Dherik