1

I am new to R Markdown and am trying to write a simple script to generate an HTML notebook. (Dictionary comes from Collections library.)

d <- dict(list(SubHeader1 = 'eqn-1', SubHeader2 = 'eqn-2a')) 
for (i in d$keys()){
  header = i
  note = d$get(i)
        
  render(input = "template.rmd", 
  output_file = "test1.html",
  params = list(header = header, note = note))
    
}

Here is my "template.rmd":

---
title: "Untitled"
author: "user"
date: "1/1/1900"
output:
  html_document:
    toc: true
    toc_float: true
params:
    header: NA
    note: NA
---

cat("##", params$header, "\n")
params$note

Here is the desired output: enter image description here

But the code gives this output: enter image description here

a11
  • 3,122
  • 4
  • 27
  • 66
  • Does this answer your question? [Parameterize both Author and Title in Markdown using a loop](https://stackoverflow.com/questions/50115403/parameterize-both-author-and-title-in-markdown-using-a-loop) – camille Apr 27 '21 at 02:43
  • Also see https://stackoverflow.com/q/31861569/5325862 – camille Apr 27 '21 at 02:44
  • @camille No, it did not, I updated the OP with the attempted answer because it did not work – a11 Apr 27 '21 at 02:46

1 Answers1

1

In the render function you can pass the values as named list using the params argument.

d <- list(SubHeader1 = 'eqn-1', SubHeader2 = 'eqn-2a')

rmarkdown::render(input = "template.rmd", 
                  output_file = "test1.html",
                  params = list(data = d))

In the RMD file declare and initialise those variables.

---
title: "Untitled"
author: "user"
date: "1/1/1900"
output:
  html_document:
    toc: true
    toc_float: true
params:
    data: NA
---


```{r, echo=FALSE, message=FALSE, warning=FALSE}
for(i in seq_along(params$data)) {
  cat(names(params$data)[i], '\n')
  cat(params$data[[i]], '\n')
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Why are you including `rmarkdown::render` inside the `for` loop? Do you need to run it for every value in the dictionary? If so, then you are overwriting `"test1.html"` everytime. – Ronak Shah Apr 27 '21 at 03:05
  • Ok..then what is the issue here? The only part that you need to change is `output_file` and make it unique for each iteration so you don't overwrite the same file. You can do that by `output_file = sprintf("test%s.html",header)`. `rmarkdown::render` doesn't return anything so it has to be remain "floating" there. – Ronak Shah Apr 27 '21 at 03:17
  • But it shouldn't be unique. It should be one file. The issue is, what code will produce the screen shot above? I am not able to generate the screenshot above with your code, I am sorry to say it – a11 Apr 27 '21 at 03:19
  • 1
    Got it. Sorry, I think I had misunderstood your question earlier. I think it is better to include the loop in markdown document instead of script. I updated the answer which does that. Although this does not give you the formatting that you need. – Ronak Shah Apr 27 '21 at 03:50