Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert code to more readable form in R

Tags:

r

I copy code from the terminal to post here. It is in following form:

> ddf2 = ddf[ddf$stone_ny>'stone',] # this is first command
> ddf2[!duplicated(ddf2$deltnr),]   # second command
   deltnr us stone_ny stone_mobility      
4    1536 63    stone         mobile 
10   1336 62    stone         mobile 

First 2 lines are commands while next 3 lines are output. However, this cannot be copied from here back to R terminal since the commands start with '> '. How can I convert this to:

ddf2 = ddf[ddf$stone_ny>'stone',] # this is first command
ddf2[!duplicated(ddf2$deltnr),]   # second command
#   deltnr us stone_ny stone_mobility      
#4    1536 63    stone         mobile 
#10   1336 62    stone         mobile 

So that it become suitable for copying from here.

I tried:

text
[1] "> ddf2 = ddf[ddf$stone_ny>'stone',] # this is first command\n> ddf2[!duplicated(ddf2$deltnr),]   # second command\n   deltnr us stone_ny stone_mobility      \n4    1536 63    stone         mobile \n10   1336 62    stone         mobile "


text2 = gsub('\n','#',text)
text2 = gsub('#>','\n',text2)
text2 = gsub('#','\n#',text2)
text2
[1] "> ddf2 = ddf[ddf$stone_ny>'stone',] \n# this is first command\n 
ddf2[!duplicated(ddf2$deltnr),]   \n# second command\n#   deltnr us stone_ny stone_mobility      \n#4    1536 63    stone         mobile \n#10   1336 62    stone         mobile "

But it cannot get pasted to the terminal.

like image 615
rnso Avatar asked Sep 27 '14 01:09

rnso


People also ask

What does plus mean in R?

This is where you'll type R Commands to immediately execute one command at a time. If a plus sign ("+") appears while in the console, it means that R is wanting you to enter some additional information. Press escape ("esc") and hit return to get back to the ">" prompt.

How do I open a file in R?

Click on the Open an existing file icon in the RStudio toolbar. A Choose file dialog will open. Select the R script you want to open [this is one place where the . R file extension comes in handy] and click the Open button.

How do I use an R code?

You type R code into the bottom line of the RStudio console pane and then click Enter to run it. The code you type is called a command, because it will command your computer to do something for you. The line you type it into is called the command line.


1 Answers

I've been waiting for an opportunity to share this function I keep in my .Rprofile file. While it may not answer exactly your question, I feel it is accomplishing something very close to what you are after. So you might get some ideas by looking at its code. And others might find it useful just as it is. The 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 function is what allows me to quickly format my answers to questions on this very website, StackOverflow. My workflow is as follows:

1) In RStudio, write my answer in an untitled script (that's the top-left quadrant). For example:

## 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) Near the top, click the "Source" button. It will execute the code in the console which is not really what we are after: rather, it will have the side effect of saving the code to the default file '~/.active-rstudio-document'.

3) Run SO() from the console (bottom-left quadrant) which will source the code (again...) from the saved file, capture the output and print it in a SO-friendly format:

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)
    }
    # [1] 0
    # [1] 0.2875775

And voila.

4) Copy-paste into stackoverflow and done.

Note: For code that takes a while to run, you can avoid running it twice by saving your script to a file (e.g. 'xyz.R') instead of clicking the "Source" button. Then run SO("xyz.R").

like image 191
flodel Avatar answered Sep 26 '22 20:09

flodel