Home > database >  Split Rmarkdown (.Rmd) file into mutiple files (.Rmd)
Split Rmarkdown (.Rmd) file into mutiple files (.Rmd)

Time:08-13

I made a big Rmarkdown (.Rmd) file that contains only chunks of R codes. I'm wondering if there's a way to automatically generate a (.Rmd) file for every chunk or if I have to manually create a (.Rmd) file for every chunk I have (over 200 chunks).

Let's say I have this (.Rmd) file :

---
title: "Untitled"
output: html_document
date: '2022-08-13'
---

R Markdown

``{r cars}
summary(cars)
``

Including Plots

``{r pressure, echo=FALSE}
plot(pressure)
``

Is there a way to generate automatically a (.Rmd) file for the chuck r cars and another for the chunk r pressure?

Thanks in advance.

CodePudding user response:

A possible solution is to use package parsemd:

library(parsermd)

rmd <- parse_rmd("x.Rmd")

rlabels <- c("cars", "pressure")

yaml <- rmd_select(rmd, has_type("rmd_yaml_list"))

for (i in rlabels)
{
  rchunk <- rmd_select(rmd, all_of(i)) 
  sink(paste0(i, ".Rmd"))
  cat(as_document(yaml), sep = "\n")
  cat(as_document(rchunk), sep = "\n")
  sink()  
}

CodePudding user response:

You have to do this manually. There is no function in R Markdown to split document automatically.

  • Related