Created
January 8, 2014 00:31
-
-
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
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
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")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just learned this is similarly done by knitr::spin