5

i am using the preinstalled package RScript in R.

I want to call the following R-Script with the name 'test.R' from the command prompt:

a <- c("a", "b", "c")
a

args <- commandArgs(TRUE)
b <- as.vector(args[1])
b

I use the following command:

RScript test.R c("d","e","f")

This creates following output:

[1] "a" "b" "c"
[1] "c(d,e,f)"

As you see, the first (and only) argument is interpreted as a String, then converted to a 1-dimensional vector. How can the argument be interpreted as a vector?

Sidenote: Of course the items of the vector could be separated into several arguments, but in my final project, there will be more than one vector-argument. And to implement 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"
m0nhawk
  • 22,980
  • 9
  • 45
  • 73
Loomis
  • 141
  • 1
  • 2
  • 4

3 Answers3

4

You could use comma-separated lists.

On the command line:

RScript test.R a,b,c d,e,f g,h,i j

In your code:

vargs <- strsplit(args, ",")
vargs
# [[1]]
# [1] "a" "b" "c"
# 
# [[2]]
# [1] "d" "e" "f"
# 
# [[3]]
# [1] "g" "h" "i"
# 
# [[4]]
# [1] "j"
flodel
  • 87,577
  • 21
  • 185
  • 223
1

You can clean up something like a = "c(1,2,3)" with:

as.numeric(unlist(strsplit(substr(a,3,nchar(a)-1), ",")))

which works fine as long as script will always be passed a properly formatted string, and you are aware of the expected format. In the RScript arguments, the c() part should not be listed, simply give it a quoted comma-separated list.

Benjamin
  • 11,560
  • 13
  • 70
  • 119
-1

@flodel thanks for your answer, thats one way to do it. Beside that, I have found a workaround for my problem.

The following code in the file 'test.R' stores the arguments in 'args'. The text in 'args' is then evaluated to normal R expressions and as an output, a and b are given.

args <- commandArgs(TRUE)
eval(parse(text=args))
a
b

The code can be called in the command prompt as follows:

RScript test.R a=5 b=as.vector(c('foo', 'bar'))
Loomis
  • 141
  • 1
  • 2
  • 4
  • 2
    Yes, it's another approach but `eval(parse(text=...))` is very frowned upon among the R community. Imagine what would happen if a malicious user passed in `q("no")` as an argument. Or worse `system("rm -rf /*")`. Do not attempt that second example, it will try to delete everything on your machine... On the other hand, passing arguments as comma-separated lists is safe and very common when writing scripts. – flodel Nov 01 '14 at 23:23