Search code examples
rsysteminvoke

How to invoke the OS command (shell file) with argument in R


I like to invoke the OS command (running a shell file in linux) within R code and send argument together that I got in the R code. For example, MyRcode.R will do some calculation and get a vector output. Then, MyRcode.R will use for loop to run a shell file and send each element in the vector. Here is a simple example of code.

[MyRcode.R]

############################################
### Some calculation to get myVector  ######
                   .
                   .
############################################

print(myVector)  # [1]  3  5   7
for (argument in myVector) {
    system("./Shell_RunCalculations.sh argument")
}

[Shell_RunCalculations.sh]

#!/bin/bash

module load R/3.5.1-gcc5.2.0

echo "argument: " $1 

Rscript --vanilla RunCalculation.R $1

[RunCalculation.R]

### This is very complex calculation which should run in Supercomputer.

First, in the shell file, I expected to print

argument: 3
argument: 5
argument: 7

However, it printed out

argument: argument
argument: argument
argument: argument

I think I did something wrong in 'system' function in R code. How can I invoke the OS command and send argument together?

The reason I am testing this is because I want to obtain myVector in MyRcode.R, and submit slurm job and send the myVector elements as arguments. The slurm job will run another R code in supercomputer clusters (parallel running) with the received arguments.

Thank you,


Solution

  • You could use

    • system2() or
    • system() in combination with paste()

    to execute a shell command from R. In the following example, the shell command echo is called from R with a string argument.

    arg <- "I am an R argument."
    system2("echo", arg)
    I am an R argument.
    

    or

    system(paste("echo", arg))
    I am an R argument.