How to run R codes inside shell script?

2019-04-30 01:07发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

This works for me in Cygwin on Windows:

#!/cygdrive/c/Progra~1/R/R-3.3.0/bin/x64/Rscript.exe

# dummy example

cat("Hello StackOverflow\n")


回答4:

Start R with the command R and then just add youre code

user@ubuntu:~/RCode/RCode$ R
> source("data_acquisition.R")
> load_libraries()
> df <- acquire_nps()
> head(df)
...


标签: r shell sh