Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

command line arguments in bash to Rscript

Tags:

bash

arguments

r

I have a bash script that creates a csv file and an R file that creates graphs from that.

At the end of the bash script I call Rscript Graphs.R 10

The response I get is as follows:

Error in is.vector(X) : subscript out of bounds
Calls: print ... <Anonymous> -> lapply -> FUN -> lapply -> is.vector
Execution halted

The first few lines of my Graphs.R are:

#!/bin/Rscript
args <- commandArgs(TRUE)
CorrAns = args[1]

No idea what I am doing wrong? The advice on the net appears to me to say that this should work. Its very hard to make sense of commandArgs

like image 810
samar Avatar asked Dec 28 '10 17:12

samar


People also ask

How do I run a Rscript in bash?

Use Rscript to run R from bash You can run it using Rscript test. r . And even better, if you add an initial shebang line #!/usr/bin/env Rscript in the script above and make it executable with chmod +x test. r , you can directly launch your R script with ./test.

How can you pass command line arguments to a script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth.

Can you run R scripts from command line?

The most convenient way to run R scripts from the command line is to use Rscript, an alternative front-end to run R code. Rscript is capable of executing R code from different command interpreters, such as a bash script on Linux or a Task Scheduler task on Windows.


1 Answers

With the following in args.R

print(commandArgs(TRUE)[1])

and the following in args.sh

Rscript args.R 10

I get the following output from bash args.sh

[1] "10"

and no error. If necessary, convert to a numberic type using as.numeric(commandArgs(TRUE)[1]).

like image 130
moinudin Avatar answered Oct 08 '22 01:10

moinudin