Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to paste documented R code into R console or Rstudio without the arrow or plus signs being registered?

Tags:

r

This will make more sense with an example. Typical R manuals from CRAN show R code with a line starting with > and indentations indicated with +. See http://cran.r-project.org/web/packages/doMC/vignettes/gettingstartedMC.pdf for an example.

The trouble is that you can't cut and paste that into a console without copying it into an editor and removing those arrow and plus characters. Is there an easier way to execute that text as R code? I figured that somebody must have dealt with this problem. Otherwise, I guess I'll write a script.

like image 281
Dave31415 Avatar asked Dec 17 '12 06:12

Dave31415


1 Answers

The writing has already been done.

2009 post by Duncan Murdoch:

CleanTranscript <- function(lines) {
         lines <- grep("^[[:blank:]]*[^>+[:blank:]]*[>+]", lines, value = TRUE) 
         lines <- sub("^[[:blank:]]*[^>+[:blank:]]*[>+] ?", "", lines) }

source(textConnection(CleanTranscript(
       # This is the Windows input strategy
       readLines("clipboard")
       # See below for Mac version
                      )), 
                      echo = TRUE, max.deparse.length=Inf) 

Subsequent 2009 R-help post by Gabor Grothendieck:

process.source <- function(action = c("both", "run", "show"), echo = TRUE,
    max.deparse.length = Inf, ...) { 
    # This is the Mac input strategy
    L <- readLines(pipe("pbpaste"))
    #  for Windows devices use
    #  L <- readLines("clipboard")
    rx <- "^[[:blank:]]*[^>+[:blank:]]*[>+]" 
    is.cmd <- grepl(rx, L) 
    L[is.cmd] <- gsub(paste(rx, "?"), "", L[is.cmd]) 
    L[!is.cmd] <- paste("#", L[!is.cmd]) 
    action <- match.arg(action) 
  if (action != "run") for(el in L) cat(el, "\n") 
  if (action == "both") cat("##################################\n") 
  if (action != "show") 
       source(textConnection(L), echo = echo, 
       max.deparse.length = max.deparse.length, ...) 
invisible(L) }

Note: The upvotes prompted me to post this as a "feature request" on the RStudio Discussion Board. Although I have not broken it yet, it might need more testing if it were to be built in to the RStudio framework.

like image 120
IRTFM Avatar answered Oct 26 '22 00:10

IRTFM