Run a R script from terminal

Let a.R being: 
sayHello <- function(){
   print('hello')
}


sayHello()

In terminal, enter:

Rscript a.R
[1] "hello"

Or:

R CMD BATCH a.R

Nothing is shown because the stdout() is store in a file:

cat a.Rout to see the result. It is not very friendly:

MacBook-Air-de-Marc:Documents marcgirondot$ cat a.Rout

R version 3.4.2 beta (2017-09-19 r73321) -- "Short Summer"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin15.6.0 (64-bit)

R est un logiciel libre livré sans AUCUNE GARANTIE.
Vous pouvez le redistribuer sous certaines conditions.
Tapez 'license()' ou 'licence()' pour plus de détails.

R est un projet collaboratif avec de nombreux contributeurs.
Tapez 'contributors()' pour plus d'information et
'citation()' pour la façon de le citer dans les publications.

Tapez 'demo()' pour des démonstrations, 'help()' pour l'aide
en ligne ou 'help.start()' pour obtenir l'aide au format HTML.
Tapez 'q()' pour quitter R.

> sayHello <- function(){
+    print('hello')
+ }
> sayHello()
[1] "hello"
> proc.time()
utilisateur     système      écoulé 
      0.193       0.045       0.292 

Now other solution. First locate Rscript:

locate Rscript

/Library/Frameworks/R.framework/Versions/3.3/Resources/Rscript
/Library/Frameworks/R.framework/Versions/3.3/Resources/bin/Rscript
/Library/Frameworks/R.framework/Versions/3.3/Resources/man1/Rscript.1
/Library/Frameworks/R.framework/Versions/3.4/Resources/Rscript
/Library/Frameworks/R.framework/Versions/3.4/Resources/bin/Rscript
/Library/Frameworks/R.framework/Versions/3.4/Resources/man1/Rscript.1
/usr/local/bin/Rscript

The version in /usr/local/bin/Rscript in a symbolic link to the current version.

Add the shebang #!/usr/local/bin/Rscript to the a.R file:

cat a.R
#!/usr/local/bin/Rscript

sayHello <- function(){
   print('hello')
}

sayHello()

Make a.R being executable
chmod 755 a.R
or
chmod +x a.R

And enter in terminal:

./a.R
[1] "hello"

It works !

More information here:



Commentaires

Posts les plus consultés de ce blog

Standard error from Hessian Matrix... what can be done when problem occurs

stepAIC from package MASS with AICc

Install treemix in ubuntu 20.04