require(knitr) # Figure out which version of Stata is available if (file.exists("C:/Program Files (x86)/Stata14/StataMP-64.exe")) { statapath <- "C:/Program Files (x86)/Stata14/StataMP-64.exe" } else if (file.exists("C:/Program Files (x86)/Stata15/StataSE-64.exe")) { statapath <- "C:/Program Files (x86)/Stata15/StataSE-64.exe" } # Set universal chunk options opts_chunk$set(engine="stata", engine.path=statapath, comment=NA) # Define a "collectcode" chunk option knit_hooks$set(collectcode = function(before, options, envir) { if (!before) { if (options$engine == "stata") { profile <- file("profile.do", open="at") writeLines(options$code, profile) close(profile) } } }) # Always hide SOME Stata commands in the echoed source, # e.g. "graph export" hook_source <- knit_hooks$get("source") knit_hooks$set(source = function(x, options) { if (options$engine == "stata") { y <- strsplit(x, "\n")[[1]] # Find and remove graph export in Stata source graphexport <- grep("^graph export.*", y) if (length(graphexport)>0) {y <- y[-(graphexport)]} # Now treat the result as regular source code hook_source(y, options) } else { hook_source(x, options) } }) # Always clean Stata commands from the output hook_output <- knit_hooks$get("output") knit_hooks$set(output = function(x, options) { if (options$engine == "stata") { y <- strsplit(x, "\n")[[1]] # Find output lines that are commands commandlines <- grep("^\\.", y) if (length(commandlines)>0) {y <- y[-(grep("^\\.", y))]} # Some commands have a leading space? if (length(grep("^[[:space:]*]\\.", y))>0) { y <- y[-(grep("^[[:space:]*]\\.", y))] } # Ensure a trailing blank line if (length(y)>0 && y[length(y)] != "") { y <- c(y, "") } # Remove blank lines at the top of the Stata log firsttext <- min(grep("[[:alnum:]]", y)) if (firsttext != Inf) {y <- y[-(1:(firsttext-1))]} # Now treat the result as regular output hook_output(y, options) } else { hook_output(x, options) } })