Rstudio difference between run and source

An important implication of @AndyClifton's answer is:

Rstudio breakpoints work in source (Ctrl-Shift-S) but not in run (Ctrl-Enter)

Presumably the reason is that with run, the code is getting passed straight into the console with no support for a partial submission.

You can still use browser() though with run though.

print() to console is supported in debugSource (Ctrl-Shift-S) as well as run.


Run and source have subtly different meanings. According to the RStudio documentation,

The difference between running lines from a selection and invoking Source is that when running a selection all lines are inserted directly into the console whereas for Source the file is saved to a temporary location and then sourced into the console from there (thereby creating less clutter in the console).

Something to be aware of, is that sourcing functions in files makes them available for scripts to use. What does this mean? Imagine you are trying to troubleshoot a function that is called from a script. You need to source the file containing the function, to make the changes available in the function be used when that line in the script is then run.

A further aspect of this is that you can source functions from your scripts. I use this code to automatically source all of the functions in a directory, which makes it easy to run a long script with a single run:

# source our functions
code.dir <- "c:\temp"
code.files = dir(code.dir, pattern = "[.r]")
for (file in code.files){
  source(file = file.path(code.dir,file))
}

Sometimes, for reasons I don't understand, you will get different behavior depending on whether you select all the lines of code and press the run the button or go to code menu and chose 'source.' For example, in one specific case, writing a gplot to a png file worked when I selected all my lines of code but the write failed to when I went to the code menu and chose 'source.' However, if I choose 'Source with Echo,' I'm able to print to a png file again.

I'm simply reporting a difference here that I've seen between the selecting and running all your lines and code and going to code menu and choosing 'source,' at least in the case when trying to print a gplot to a png file.

Tags:

Rstudio