R: RScript Vector as argument
I am using the pre-installed RScript package in R.
I want to call the following R-Script named "test.R" from the command line:
a <- c("a", "b", "c")
a
args <- commandArgs(TRUE)
b <- as.vector(args[1])
b
I am using the following command:
RScript test.R c("d","e","f")
This creates the following output:
[1] "a" "b" "c"
[1] "c(d,e,f)"
As you can see, the first (and only) argument is interpreted as a string and then converted to a one-dimensional vector. How can an argument be interpreted as a vector?
Sidenote: Of course, vector elements can be split into multiple arguments, but my final project will have more than one vector argument. And implementing something like this is my last resort:
RScript test.R "d" "e" "f" END_OF_VECTOR_1 "g" "h" "i" END_OF_VECTOR_2 "j" "k" "l"
source to share
You can clean up something like a = "c(1,2,3)"
with
as.numeric(unlist(strsplit(substr(a,3,nchar(a)-1), ",")))
which works great as long as the script is always passed in a properly formatted string and you know the expected format. The part c()
does not need to be specified in RScript arguments , just give it a comma separated list.
source to share
@flodel thanks for your answer, this is one way to do it. Also, I found a workaround for my problem.
The following code in the file 'test.R' stores the arguments in 'args'. Then the text in 'args' is evaluated against normal R-expressions and the values a and b are given as output.
args <- commandArgs(TRUE)
eval(parse(text=args))
a
b
The code can be called on the command line as follows:
RScript test.R a=5 b=as.vector(c('foo', 'bar'))
source to share