Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run R codes inside shell script?

Tags:

shell

sh

r

I have a R file ( myfile.R). I want to run it using a shell script. How Can I do that? I tried this:

#! /bin/bash
Rscript myfile.R

but it gives me this error: Rscript: command not found

I also tried this:

#! /bin/bash
R --not-save-- < myfile.R 

It also gives this error: R : command not found

What is the best way to do that?

like image 460
user1080814 Avatar asked Jul 08 '14 22:07

user1080814


People also ask

How do I run an R in shell script?

Use Rscript to run R from bash R comes with Rscript , a command line tool that can run R scripts or R commands directly from the bash shell. You can run it using Rscript test. r . And even better, if you add an initial shebang line #!/usr/bin/env Rscript in the script above and make it executable with chmod +x test.

How do I run an R code in terminal?

Starting R If R has been installed properly, simply entering R on the command line of a terminal should start the program. In Windows, the program is typically specified as the action performed when clicking on an icon. You can also use this method on a *NIX system that has a window manager such as KDE.

How do I run code in RStudio script?

You create new R Script by clicking on File > New File > R Script in the RStudio menu bar. To execute your code in the R script, you can either highlight the code and click on Run, or you can highlight the code and press CTRL + Enter on your keyboard.


2 Answers

The idea is to not write a shell but to write an R script. That is what Rscript is for, and our littler package offered /usr/bin/r even before that.

So just do

 #!/usr/bin/Rscript

 cat("Hello, world\n")
 # rest of your code below 

or use

 #!/usr/bin/r

for littler -- I have multiple cron jobs doing just that.

This obviously assumes that you'd have Rscript or r in /usr/bin as you would e.g. on a regular Debian or Ubuntu box.

like image 134
Dirk Eddelbuettel Avatar answered Nov 15 '22 07:11

Dirk Eddelbuettel


I think what you're looking for is batch mode. You can do that, like this:

R CMD BATCH [options] infile [outfile] &

You can read more about batch mode here.

like image 45
donicamm Avatar answered Nov 15 '22 07:11

donicamm