How to run R codes inside shell script?

2019-04-30 00:47发布

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?

标签: r shell sh
4条回答
别忘想泡老子
2楼-- · 2019-04-30 01:13

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楼-- · 2019-04-30 01:13

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")
查看更多
Animai°情兽
4楼-- · 2019-04-30 01:14

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.

查看更多
太酷不给撩
5楼-- · 2019-04-30 01:14

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)
...
查看更多
登录 后发表回答