Removing YAML from an RMD file through an R script

So you want to write a book from many RMD files using bookdown.  Here is an R script that strips the YAML lines of an Rmd file because bookdown does not accept files with its own YAML. A new file is created that has no YAML.  The program is written just for one Rmd file, and I will be writing an extension of it to do this for a whole directory including subdirectories.  I will soon write a script that will move the YAML absent RMD files and associated sub-directories to a new directory of its own.

# A program to remove YAML from an RMD file. 
# It can be modified to do this for all
# files in a directory and/or its subdirectories 
# Stay tuned for the update.

#Set the working directory

# filename of the rmd file whose YAML you want to take out
fileName <- "Chapter01.03RoundoffErrors/0103RoundOffErrorsYaml.rmd"

# Open the file to read
Input_File <- file(fileName,open="r")
linn <-readLines(Input_File)

# icapture is a vector which will check the two lines 
# that have --- in them.
icapture <- vector(,10)

# Just printing the lines in the rmd file, not needed.
#for (i in 1:length(linn)){
# print(linn[i])

#The name of the file which will store YAML free RMD file.
YAML_Remove_File <- file("Chapter01.03RoundoffErrors/0103RoundOffErrorsYamlRemove.rmd",open="w")

j <- 0
#Capturing the two line numbers where --- exists
for (i in 1:length(linn)){
if(strtrim(linn[i],3) == "---"){
j <- j+1
icapture[j] <- i

# Write to the output file only if it has already captured two --- 
if ((j==2) & (i!=icapture[2])){

#close the input and output files


This post is brought to you by

Leave a Reply