1

In the Unix script, is there any way to run R files but with arguments in the Unix script?

I know that to run R files in that system, you will need to type "R -f "file" but what codes do you need in R so that you will need to type this instead on Unix:

"R -f "file" arg1 arg2"

1
  • I edited the questions now. Commented Feb 16, 2017 at 22:50

2 Answers 2

1

Here is an example. Save this code in test.R:

#!/usr/bin/env Rscript
# make this script executable by doing 'chmod +x test.R'
help = cat(
"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Help text here
Arguments in this order:
    1) firstarg
    2) secondarg
    3) thirdarg
    4) fourtharg
./test.R firstarg secondarg thirdarg fourtharg
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\n\n")

# Read options from command line
args = commandArgs(trailingOnly = TRUE)
if(is.element("--help", args) | is.element("-h", args) | is.element("-help", args) | is.element("--h", args)){
    cat(help,sep="\n")
    stop("\nHelp requested.")
}

print(args)

Do chmod +x test.R Then invoke it using ./test.R a b c d. It should print: [1] "a" "b" "c" "d".

You can access each of the args by doing args[1] to get to a and args[4] to get to d.

Sign up to request clarification or add additional context in comments.

Comments

0

The suggestion to use Rscript does seem useful but possibly not what is being asked. One can also start R from the command line with an input file that gets sourced. The R interpreter can access the commandArgs in that mode as well. This is a minimal "ptest.R" file in my user directory that is also my default working directory:

ca <- commandArgs()
print(ca)

From a Unix command line I can do:

$ r -f ~/ptest.r --args "test of args"

And R opens, displays the usual startup messages and announces packages loaded by .Rprofile and then:

> ca <- commandArgs()
> print(ca)
[1] "/Library/Frameworks/R.framework/Resources/bin/exec/R"
[2] "-f"                                                  
[3] "/Users/davidwinsemius/ptest.r"                       
[4] "--args"                                              
[5] "test of args"                                        
> 
> 

And then quits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.