Source R File

In this tutorial we look at how to Source R File from the console. R commands can be run from a file using the source command.

create a test file called test.R

vi test.R

add the following line in the file

cat("Sourcing from R file\n")

Now open R and fire this command (give the absolute or relative path to the file)

> source("test.R")
Sourcing from R file
> 

You might also want to see what commands are being fired. use echo=true

> source("test.R",echo=TRUE)
> cat("Sourcing from R file\n")
Sourcing from R file
>

In this case the second line comes from the test.R file and is not typed on the console.

If you need even more information of how the processing is being done, use verbose = true

> source("test.R",echo=TRUE)
> cat("Sourcing from R file\n")
Sourcing from R file
> source("test.R",verbose=TRUE)
'envir' chosen:<environment: R_GlobalEnv>
encoding = "native.enc" chosen
--> parsed 1 expressions; now eval(.)ing them:

>>>> eval(expression_nr. 1 )
		 =================

> cat("Sourcing from R file\n")
Sourcing from R file
curr.fun: symbol cat
 .. after 'expression(cat("Sourcing from R file\n"))'
> 



Couple of things to note

  • The complete file is parsed before the code is run so either all code runs or none.
  • If an error occurs in a file that has correct syntax then all objects created till the error will be available.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.