How to run R codes inside shell script?

自作多情 提交于 2019-12-10 13:58: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?


回答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)
...



回答5:


Considering that you have installed R in your machine (Linux based), I feel below are the steps you can follow to run R in sh file.

OS : Mac-Os (Mojave version)

R-version : 3.6

step 1 : I have installed R in my mac machine using brew.

$ brew install r (-- This will install latest R into your machine --)

step 2 : create sample sh file. (startR.sh)

$ touch startR.sh

step 3 : copy below contents into your startR.sh file

$ vim startR.sh

(Paste below contents)

#!/bin/sh
Rscript sample.r
echo " r sample run"
exit

( --- I have created simple R file with name sample.R with below contents --)

sayHello <- function(){

print('hello') }

sayHello()

( This is simple hello function, please feel free to change this with your actual functions)

note : please place your sample.R in same location as that of startR.sh

step 4 : change permission to .sh file

$ chmod 750 startR.sh

step 5 : execute .sh file

$ sh startR.sh

If everything goes fine, it should print below output.

During startup - Warning messages: 1: Setting LC_COLLATE failed, using "C" 2: Setting LC_TIME failed, using "C" 3: Setting LC_MESSAGES failed, using "C" 4: Setting LC_MONETARY failed, using "C" 1 "hello" r sample run



来源:https://stackoverflow.com/questions/24642281/how-to-run-r-codes-inside-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!