Home > Enterprise >  Knit each RMarkdown file inside a given folder
Knit each RMarkdown file inside a given folder

Time:09-06

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!

CodePudding user response:

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 file will be found in the multiple_rmd directory.

CodePudding user response:

You could do

files <- list.files(pattern = "\\.Rmd$")

purrr::map(files, ~rmarkdown::render(
  .x
))
  • Related