komodovaran_
komodovaran_

Reputation: 2012

Run code spread over multiple lines in single keystroke [r]

Coding/R noob here.

Say that I want to plot a histogram of my data. To keep it tidy (for me, at least) I've split the parameters over multiple lines:

hist(data,
    density=20,     
    ylim=c(0,1),
    xlim=c(0,1),  
    freq=FALSE,
    xlab="X axis",
    ylab="Y axis",
    breaks=25)

curve(dnorm(x,mean, sd),
    col="black",
    add=TRUE,
    lwd=1.5)

Now I want to change just one or two of the parameters, and then re-run this whole sequence. If I had everything on one line I could run it all with one keystroke. Now R wants no less than 8 keystrokes to re-run this specific section of code. I could of course select the whole block and run it, but that seems a bit fiddly. I could also use "run previous", but that also gets a bit messy when superimposing graphs, since R doesn't have an "undo plot", so you need to re-run everything if your line width is too broad the first time around.

Is there another way, a la { } or something?

Upvotes: 1

Views: 5042

Answers (3)

Corey Levinson
Corey Levinson

Reputation: 1651

In the RStudio version I am using, this has changed again. I fixed it by going to Tools > Global Options > Code. Then checking "Focus Console After Executing Code"

Upvotes: 0

Al14
Al14

Reputation: 1814

In R studio select Preferences and click on code. Under editing there is the Execution tick "Execute all lines in a statement".

This will allow you to run all the multiple lines of your single script

Upvotes: 1

Jonathan
Jonathan

Reputation: 8832

The preview version of RStudio is a lot smarter about statement execution. Ctrl+Enter (or Cmd+Enter on OS X) will execute your whole statement no matter how many lines it's spread over. You can download the preview here:

https://www.rstudio.com/products/rstudio/download/preview/

This should get you down to two or three keystrokes.

If you want to do it with a single keystroke, you can annotate the code with a section header and then use RStudio's Run Code Section command. More on that here:

https://support.rstudio.com/hc/en-us/articles/200484568-Code-Folding-and-Sections

Upvotes: 3

Related Questions