Created
August 14, 2019 16:44
-
-
Save jananiravi/0c545308de3418f83e6c35cb536f3051 to your computer and use it in GitHub Desktop.
rmd2rscript: a function to convert R Markdown to an R script which can be sourced script for converting .Rmd files to .R scripts. (~ Kevin Keenan)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' ## rmd2rscript: a function to convert R Markdown to an R script which can be sourced | |
#' ## script for converting .Rmd files to .R scripts. | |
#' ## Author: Kevin Keenan 2014 | |
#' ## http://rstudio-pubs-static.s3.amazonaws.com/12734_0a38887f19a34d92b7311a2c9cb15022.html | |
#' ## Slightly modified by: Janani Ravi 2019 | |
#' | |
#' This function will read a standard R markdown source file and convert it to | |
#' an R script to allow the code to be run using the "source" function. | |
#' | |
#' The function is quite simplisting in that it reads a .Rmd file and adds | |
#' comments to non-r code sections, while leaving R code without comments | |
#' so that the interpreter can run the commands. | |
#' | |
#' | |
rmd2rscript <- function(infile){ | |
# read the file | |
flIn <- readLines(infile) | |
# identify the start of code blocks | |
cdStrt <- which(grepl(flIn, pattern = "```{r*", perl = TRUE)) | |
# identify the end of code blocks | |
cdEnd <- sapply(cdStrt, function(x){ | |
preidx <- which(grepl(flIn[-(1:x)], pattern = "```", perl = TRUE))[1] | |
return(preidx + x) | |
}) | |
# define an expansion function | |
# strip code block indicators | |
flIn[c(cdStrt, cdEnd)] <- "" | |
expFun <- function(strt, End){ | |
strt <- strt+1 | |
End <- End-1 | |
return(strt:End) | |
} | |
idx <- unlist(mapply(FUN = expFun, strt = cdStrt, End = cdEnd, | |
SIMPLIFY = FALSE)) | |
# add comments to all lines except code blocks | |
comIdx <- 1:length(flIn) | |
comIdx <- comIdx[-idx] | |
for(i in comIdx){ | |
flIn[i] <- paste("#' ", flIn[i], sep = "") | |
} | |
# create an output file | |
# with date of conversion (comment line 45 to omit this) | |
nm <- strsplit(infile, split = "\\.")[[1]][1] | |
flOut <- file(paste(nm, | |
"_rmd2r_", format(Sys.time(), "%Y%m%d"), | |
".R", sep = ""), "w") | |
for(i in 1:length(flIn)){ | |
cat(flIn[i], "\n", file = flOut, sep = "\t") | |
} | |
close(flOut) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment