Statamarkdown icon indicating copy to clipboard operation
Statamarkdown copied to clipboard

Feature Request: purl-style function for stata code

Open davidaarmstrong opened this issue 5 months ago • 1 comments

I wonder if there is any value in making a knitr::purl-style function that outputs a .do file with just the Stata code in it? I've done this for my own files. Not sure it is sufficiently robust for production, but might be a good start if you're inclined to add something like this to the package. One thing this doesn't do that purl() does is capture the chunk options and return them either as comments or roxygen documentation tags.

purl_do <- function(fname, ...){
  rl <- readLines(fname)
  starts <- grep("^```\\{stata", rl)
  if(length(starts) > 0) {
    ends <- which(rl == "```")
    ends <- sapply(starts, \(x)min(ends[which(ends > x)]))
    starts <- starts+1
    ends <- ends-1
    res <- lapply(seq_along(starts), \(i)rl[starts[i]:ends[i]])
    outfile <- gsub("(.*)\\.[Rr]md$", "\\1.do", fname)
    for(i in seq_along(res)){
      cat(res[[i]], sep="\n", file=outfile, append=TRUE)
      cat("\n\n", file=outfile, append=TRUE)
    }
  }else{
    stop("No Stata code in document.\n")
  }
}

davidaarmstrong avatar Sep 20 '24 16:09 davidaarmstrong