Split a Rmd or Qmd file into a tibble and vice-versa

statnmap

2021-01-23

library(lightparser)

Parse and split a Rmd / Qmd file, and transform as tibble

{lightparser} reads your flat file to detect what is a yaml header, what is a code chunk and its options, what is a text part.
Function split_to_tbl() returns a tibble with all these parts.

file <- system.file(
  "dev-template-parsing.Rmd",
  package = "lightparser"
)
split_to_tbl(file)
#> It seems you are currently knitting a Rmd/Qmd file. The parsing of the file will be done in a new R session.
#> # A tibble: 35 × 8
#>    type    label       params       text     code  heading heading_level section
#>    <chr>   <chr>       <list>       <named > <lis> <chr>           <dbl> <chr>  
#>  1 yaml    <NA>        <named list> <lgl>    <lgl> <NA>               NA <NA>   
#>  2 inline  <NA>        <lgl [1]>    <chr>    <lgl> <NA>               NA <NA>   
#>  3 block   development <named list> <lgl>    <chr> <NA>               NA <NA>   
#>  4 inline  <NA>        <lgl [1]>    <chr>    <lgl> <NA>               NA <NA>   
#>  5 heading <NA>        <lgl [1]>    <chr>    <lgl> Descri…             1 Descri…
#>  6 inline  <NA>        <lgl [1]>    <chr>    <lgl> <NA>               NA Descri…
#>  7 block   description <named list> <lgl>    <chr> <NA>               NA Descri…
#>  8 inline  <NA>        <lgl [1]>    <chr>    <lgl> <NA>               NA Descri…
#>  9 heading <NA>        <lgl [1]>    <chr>    <lgl> Read d…             1 Read d…
#> 10 inline  <NA>        <lgl [1]>    <chr>    <lgl> <NA>               NA Read d…
#> # ℹ 25 more rows

Combine a parsed tbl Rmd / Qmd file into a new file

You can re-create the Rmd/Qmd file from the tibble returned by split_to_tbl(). As this is a tibble, before combining it as a new file, you can modify its content by removing or adding rows, replacing content, etc.

file <- system.file("dev-template-parsing.Rmd",
  package = "lightparser"
)
# split first
tbl_rmd <- split_to_tbl(file)
#> It seems you are currently knitting a Rmd/Qmd file. The parsing of the file will be done in a new R session.
# apply your filters
tbl_rmd_filtered <- tbl_rmd[-5, ]
# combine then
combine_tbl_to_file(tbl_rmd_filtered, tempfile(fileext = ".Rmd"))