3

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!

3 Answers 3

3

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"
Sign up to request clarification or add additional context in comments.

Comments

1

I think I understand what you're trying to do here, let me know if I'm wrong.

I created an R script (called script.R) that contains the following:

args <- commandArgs(TRUE)
eval(parse(text=args[1]))
print(myarray)

I can then call the script like this (from my command line)

Rscript script.R myarray="c(1,3,4)"

As you can see, the argument gets passed (in your script you could do print(args) to see what gets passed and how), I use eval(parse(text=...))) to make it execute (create myarray in the script) and then I can do what I want with it (in my case, I printed it, but you could do analysis or other stuff). Does this help?

1 Comment

Thanks, Joy! But my problem is that I'll have to pass many arrays of hundreds of elements. So if I declare the arrays in the same command line, as in Rscript script.R myarray="c(1,3,4)" I could not declare everything I need.
1

If you have hundreds of values in the array, perhaps it'd more useful to write it to a text file and pass the file path as a parameter and have R read it in.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.