Command-line arguments: Difference between revisions

Content added Content deleted
(give an actual example!)
(improved output)
Line 1,012: Line 1,012:
Following adapted from [http://quantitative-ecology.blogspot.com/2007/08/including-arguments-in-r-cmd-batch-mode.html this post by Forester]:
Following adapted from [http://quantitative-ecology.blogspot.com/2007/08/including-arguments-in-r-cmd-batch-mode.html this post by Forester]:


Suppose you want to call your script <tt>test.r</tt> with the arguments <tt>a=1 b=c(2,5,6)</tt>, where <tt>b</tt> is a numeric vector. Suppose you also want to redirect your output to <tt>test.out</tt> (not that you have a choice: I still don't know how to make R send shell-script output to stdout). You would then run
Suppose you want to call your script <tt>test.r</tt> with the arguments <tt>a=1 b=c(2,5,6)</tt>, where <tt>b</tt> is a numeric vector. Suppose you also want to redirect your output to <tt>test.out</tt> (not that you have a choice--I still don't know how to make R send shell-script output to stdout). You would then run


<lang R>R CMD BATCH --vanilla '--args a=1 b=c(2,5,6)' test.r test.out &</lang>
<lang R>R CMD BATCH --vanilla --slave '--args a=1 b=c(2,5,6)' test.r test.out</lang>


from the commandline. Your resulting output <tt>test.out</tt> would contain (e.g., if you <tt>cat</tt> it)
from the commandline. Your resulting output <tt>test.out</tt> would contain (e.g., if you <tt>cat</tt> it)


<pre>[1] 2
<pre>R version 2.14.0 (2011-10-31) [or whatever version you are running,
followed by several more lines of R startup cruft,
before it echoes your code:]
> ## Read the commandline arguments
> args <- (commandArgs(TRUE))
>
> ## args is now a list of character vectors
> ## First check to see if arguments are passed.
> ## Then cycle through each element of the list and evaluate the expressions.
> if (length(args)==0) {
+ print("No arguments supplied.")
+ # supply default values
+ a = 1
+ b = c(1,1,1)
+ } else {
+ for (i in 1:length(args)) {
+ eval(parse(text=args[[i]]))
+ }
+ }
> print(a*2)
[1] 2
> print(b*3)
[1] 6 15 18
[1] 6 15 18
>
> proc.time()
> proc.time()
user system elapsed
user system elapsed
0.168 0.026 0.178
0.168 0.026 0.178
</pre>
</pre>

If you know how to get the output

* sent to stdout (i.e., as is normal with shell scripts)
* done without the profiling

please update this example!


=={{header|RapidQ}}==
=={{header|RapidQ}}==