53

How do I run an entire R code script in RStudio?

When I click on the Run button in RStudio, the code runs only on a line-by-line basis and I want it to execute all the code at once instead of running through line by line.

So far the only method I've tried that works is selecting the entire script and then clicking the run button. The other option is running line by line.

Is there an easier way to run the entire script with a single button or a shortcut?

Jawand S.
  • 148
  • 10
alphabeta
  • 687
  • 1
  • 6
  • 7
  • Also is there a way to stop a script as its running in R studio? Or a shortcut? Sometimes it gives me a + sign thinking I have more code to give it but I actually want the code to stop. – alphabeta Oct 07 '12 at 05:12
  • My guess is that you're using RStudio because of your previous question. But this is completely editor specific. You'll need to provide more details and even then the question isn't really appropriate for SO. So before it gets closed... check the menu called "Code" - it will give you the keyboard shortcuts for various options (assuming you're using RStudio). – Dason Oct 07 '12 at 05:13
  • Hey Dason, thank you for your response, but even in regular R I still have a problem running the entire script – alphabeta Oct 07 '12 at 05:15
  • 1
    Don't forget that http://stats.stackexchange.com/ can be a useful resource as well for questions regarding R. – Austin Henley Oct 07 '12 at 05:16
  • 1
    In RGui just highlight the region you want to run and then use Ctrl-r (assuming you're using windows) – Dason Oct 07 '12 at 05:26
  • 1
    What about using `source()`. Also, if R keeps prompting you for more input, you probably have mismatched parentheses or brackets somewhere. – A5C1D2H2I1M1N2O1R2T1 Oct 07 '12 at 05:28

2 Answers2

48

Or take a look at Rscript for running R scripts from the command line. In addition, in Rstudio you can run the entire script by pressing Ctrl+Shift+Enter without selecting any code. In addition, there is a shortcut to source the current script file (Ctrl+Shift+s), which runs the script without echoing each line.

Tidoni
  • 195
  • 1
  • 4
  • 13
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • How do you install Rscript? my windows computer doesn't recognise it as a program name although I have R installed – aloea Dec 07 '21 at 16:37
28

Assuming your script is named "myScript.r", you can use something like source("myScript.r", echo = TRUE) to run the entire script.

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • How about a rmd document? – Jiaxiang Apr 12 '19 at 11:11
  • Genius, I was going crazy in VSCode selecting all and then running. Problem was it would crash most times that way, I had to start running line by line to work. Maybe it executes all the code at once when selected and causes order of operation errors, i.e lines running out of turn. Anyway now I can just cmd+ent on this one line!!!!!! – The Way Feb 25 '21 at 11:52