How to read arguments as numeric vector

814 views Asked by At

I'm having some troubles with my R script, because I want to use it from a bash script. My problem comes when I call the script and introduce its arguments, I use the following command line

Rscript myscript.R 1,2,1,3,2,3

I want to use the argument "1,2,1,3,2,3" as a numeric vector in order to use its length and elements. So in myscript.R the code is:

args <- commandArgs(trailingOnly=TRUE)
comparisons <- args[1]

but when I use this variable comparisons to other things it comes the error:

for (i in seq(from = 1, to = length(comparisons)-1, by = 2))
{
...
}

Error message:

Error in seq.default(from = 1, to = (length(comparisons) - 1), by = 2) : 
wrong sign in 'by' argument
Calls: seq -> seq.default
Execution halted

How can I read the argument comparisons as a numeric vector?

2

There are 2 answers

1
xosp7tom On BEST ANSWER

With your code, comparisions is just a one-element string vector, thus(length(comparisons) - 1) = 0. This causes, from 1 -> to 0 is decreasing, but by 2 is positive, thus seq fails.

You can use this code to convert it to a numeric vector

comparisons <- unlist(lapply(strsplit(comparisons, ","), as.numeric))
0
hrbrmstr On

The scan() function is an oft-overlooked but highly useful and versatile tool:

scan(text=args[1], sep=",", quiet=TRUE)

If you don't need doubles then:

scan(text=args[1], what=integer(), sep=",", quiet=TRUE)

will give you integers.