Rstudio difference between run and source

user2543622 picture user2543622 · May 29, 2014 · Viewed 26.2k times · Source

I am using Rstudio and not sure how options "run" and "source" are different.

I tried googling these terms but 'source' is a very common word and wasn't able to get good search results :(

enter image description here

Answer

Andy Clifton picture Andy Clifton · Jun 25, 2014

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))
}