Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass an array as argument to an R script command line run?

I'm trying to pass an array of hundreds of elements as an argument of an R script via command line in Windows. Firstly, I'd like to declare my array in some way. I'm doing that in command line:

set my_array=c(0,1,2,3,4,5,6,7,8,9,...,700)

Then I want to run my script and get the array as argument.

Rscript my_script my_array

But when I try this an error message came up saying that 'the object my_array" could not be found. I know how to get the arguments in my script, using args <- commandArgs(TRUE). I just need to recognize my declared array as an argument - or declare it in the right way and pass it in the right way as an argument to my script.

Thanks!

like image 965
Guilherme Campos Avatar asked Nov 26 '25 23:11

Guilherme Campos


1 Answers

First, i am not sure if you should use set to declare any variable in terminal, but you can see more of this on man set page.

There are some ways i think you can try to pass an array to R script, it mainly depends on how you declare the my_array in terminal.


1 - "my_array" can be a string in bash:

$ my_array="c(0,1,2,3,4)"
$ Rscript my_script ${my_array}

And use the eval(parse(text=())) in R script to transform the argument as a vector to R environment.

args <- commandArgs(trailingOnly=TRUE) 
print(args)
# c(0,1,2,3,4,5,6,7,8,9)

args <- eval(parse(text=args[1]))
print(args)
# [1] 0 1 2 3 4 5 6 7 8 9

2 - "my_array" can be an array in bash:

$ my_array=(0,1,2,3,4)
$ Rscript my_script ${my_array[*]}

and in R the args is already your array, but of type character:

args <- commandArgs(trailingOnly=TRUE) 
print(args)
# [1] "0" "1" "2" "3" "4" "5"
like image 68
Rafael Toledo Avatar answered Nov 29 '25 15:11

Rafael Toledo