Skip to content

Instantly share code, notes, and snippets.

@mikelove
Created January 8, 2014 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikelove/8309518 to your computer and use it in GitHub Desktop.
Save mikelove/8309518 to your computer and use it in GitHub Desktop.
this hastily written script converts an R script which starts with a comment into a Rmd file, splitting code into chunks and turning comments into text
script2Rmd <- function(filein) {
lns <- scan(filein,what="char",sep="\n")
comments <- substr(lns,1,1) == "#"
lnsout <- lns
lnsout[comments] <- substr(lns[comments],3,nchar(lns[comments]))
rlelens <- rle(comments)$lengths
f <- factor(rep(seq_along(rlelens),rlelens))
lnsoutsplit <- split(lnsout, f)
chunkdelims <- rep(c("\n\n```{r}","```\n\n"), length(lnsoutsplit)/2)
#from https://stat.ethz.ch/pipermail/r-help/2006-March/101023.html
interleave <- function(v1,v2)
{
ord1 <- 2*(1:length(v1))-1
ord2 <- 2*(1:length(v2))
c(v1,v2)[order(c(ord1,ord2))]
}
lnsoutchunked <- interleave(lnsoutsplit,chunkdelims)
write(do.call(c,lnsoutchunked), file=paste0(filein,"md"))
}
@mikelove
Copy link
Author

I just learned this is similarly done by knitr::spin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment