create PDF dynamically in Rmarkdown

Asked

Viewed 380 times

2

Good afternoon. For a week I’ve been trying to do a magic at Rmarkdown but I can’t. Well, come on.

Contextualizing: I need to write different Pdfs (or html) with different contents. In this case, this different content are only variables (minimum temp, maximum temp... in the pdf home these values are different). I have already made a code that takes the sql files, mounts the base for each day, and mounts different . txt with different messages.

What I need now is to SAVE different Pdfs (or html) automatically using Rmarkdown.

The justification for this is that these Pdfs/html are reports that will be sent weekly to different recipients.

summarizing: I need to create different Pdfs/Html with different content automatically.

  • Hello! Can you provide us some code you have tried and better exemplify what you want to do?

1 answer

3

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')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.