I was waiting for the opportunity to share this function stored in a .Rprofile file. Although he may not answer exactly your question, I feel that he is doing something very close to what you need. This way, you can get some ideas by looking at its code. And others may find it useful as it is. Function:
SO <- function(script.file = '~/.active-rstudio-document') { # run the code and store the output in a character vector tmp <- tempfile() capture.output( source(script.file, echo = TRUE, prompt.echo = "> ", continue.echo = "+ "), file = tmp) out <- readLines(tmp) # identify lines that are comments, code, results idx.comments <- grep("^> [#]{2}", out) idx.code <- grep("^[>+] ", out) idx.blank <- grep("^[[:space:]]*$", out) idx.results <- setdiff(seq_along(out), c(idx.comments, idx.code, idx.blank)) # reformat out[idx.comments] <- sub("^> [#]{2} ", "", out[idx.comments]) out[idx.code] <- sub("^[>+] ", " ", out[idx.code]) out[idx.results] <- sub("^", " # ", out[idx.results]) # output cat(out, sep = "\n", file = stdout()) }
This SO feature allows me to quickly format my answers to questions on this very StackOverflow website. My workflow is as follows:
1) In RStudio, write my answer in an untitled script (in the upper left quadrant). For instance:
## This is super easy, you can do set.seed(123) # initialize x x <- 0 while(x < 0.5) { print(x) # update x x <- runif(1) } ## And voila.
2) At the top of the screen, click the "Source" button. It will execute the code in the console, which is actually not what we are doing: rather, it will have the side effect of saving the code to the default file '~ / .active-rstudio-document.
3) Run SO() from the console (lower left quadrant), which will call the code (again ...) from the saved file, capture the output and print it in SO-friendly format:
This is super easy, you can do set.seed(123)
4) Copy-paste into stackoverflow and do.
Note. For code that takes some time to execute, you can not run it twice by saving the script to a file (for example, "xyz.R") instead of clicking the "Source" button. Then run SO("xyz.R") .