简体   繁体   中英

command line arguments in bash to Rscript

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

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]) .

Just a guess, perhaps you need to convert CorrAns from character to numeric, since Value section of ?CommandArgs says:

A character vector containing the name of the executable and the user-supplied command line arguments.

UPDATE: It could be as easy as:

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

Reading the docs , it seems you might need to remove the TRUE from the call to commandArgs() as you don't call the script with --args . Either that, or you need to call Rscript Graphs.R --args 10 .

Usage

commandArgs(trailingOnly = FALSE)

Arguments

trailingOnly logical. Should only arguments after --args be returned?

Rscript args.R 10 where 10 is the numeric value we want to pass to the R script.

print(as.numeric(commandArgs(TRUE)[1]) prints out the value which can then be assigned to a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM