Knit each RMarkdown file inside a given folder

Viewed 54

I have a folder with several R Markdown (.Rmd) files. Is there a way to automatically Knit each file sequentially?

Currently I have to open a file, click Knit (takes several minutes to run), close, repeat for next file...

Thanks!

2 Answers

You can do this using rmarkdown::render function in a loop. Here I have used map() from {purrr} package instead of an explicit for-loop.

Now suppose I have two rmd files inside of a directory multiple_rmd

+---multiple_rmd
|       rmarkdown_file_01.Rmd
|       rmarkdown_file_02.Rmd

Now to render them in a loop, collect the file paths (here I have used list.files function which returns the relative file paths) and pass the file paths of those rmd files to render function.

rmd_files <- list.files(path = "multiple_rmd/", full.names = TRUE)
rmd_files

# [1] "multiple_rmd/rmarkdown_file_01.Rmd"
# [2] "multiple_rmd/rmarkdown_file_02.Rmd"

purrr::map(.x = rmd_files, 
           .f = ~rmarkdown::render(.x, output_dir = "multiple_rmd/"))

Now the rendered output files will be found in the multiple_rmd directory.

You could do

purrr::map(list.files(pattern = "\\.Rmd$"), ~rmarkdown::render(.x))
Related