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!
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With