Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rstudio difference between run and source

Tags:

rstudio

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

like image 538
user2543622 Avatar asked May 28 '14 23:05

user2543622


People also ask

What is the difference between run and source in R?

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

What does source () in R do?

source causes R to accept its input from the named file or URL or connection or expressions directly.

What does it mean to source an R file?

You can use the source function in R to reuse functions that you create in another R script. This function uses the following basic syntax: source("path/to/some/file.R") Simply add this line to the top of your R script and you'll be able to use any functions defined in file.

What does source on Save do in RStudio?

When editing re-usable functions (as opposed to freestanding lines of R) you may wish to set the Source on Save option for the document (available on the toolbar next to the Save icon). Enabling this option will cause the file to automatically be sourced into the global environment every time it is saved.


1 Answers

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)) } 
like image 70
Andy Clifton Avatar answered Sep 16 '22 18:09

Andy Clifton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!