cc_staff
653
edits
(Marked this version for translation) |
(using arguments) |
||
Line 151: | Line 151: | ||
<!--T:77--> | <!--T:77--> | ||
Using the R command <tt>system()</tt> you can execute commands in the ambient environment from inside R. On Compute Canada clusters this can lead to problems because R will give an incorrect value to the environment variable <tt>LD_LIBRARY_PATH</tt>. You can avoid this problem by using the syntax <tt>system("LD_LIBRARY_PATH=$RSNT_LD_LIBRARY_PATH <my system call>")</tt> in your R system calls. | Using the R command <tt>system()</tt> you can execute commands in the ambient environment from inside R. On Compute Canada clusters this can lead to problems because R will give an incorrect value to the environment variable <tt>LD_LIBRARY_PATH</tt>. You can avoid this problem by using the syntax <tt>system("LD_LIBRARY_PATH=$RSNT_LD_LIBRARY_PATH <my system call>")</tt> in your R system calls. | ||
== Passing parameters as arguments to R scripts == | |||
Sometimes it can be useful to pass parameters as arguments to R scripts, to avoid having to either change the R script for every job or having to manage multiple copies of otherwise identical scripts. This can be useful to specify the names for input- or output-files, or maybe numerical parameters. | |||
The following example expects exactly two arguments. The first one should be a string which will be used for the variable "name" and the second one should be an integer for the variable "number". | |||
{{File | |||
|name=arguments_test.R | |||
|lang="R" | |||
|contents= | |||
# read arguments | |||
args = commandArgs(trailingOnly=TRUE) | |||
# test if there is at least two arguments: if not, return an error | |||
if (length(args)<2) { | |||
stop("At least two arguments must be supplied ('name' (text) and 'numer' (integer) )", call.=FALSE) | |||
} | |||
# assign arguments to variables | |||
name <- args[1] # read first argument as string | |||
number <- as.integer( args[2] ) # read second argument as integer | |||
# use the arguments | |||
print(paste("Processing with name:'", name, "' and number:'", number,"'", sep = '')) | |||
}} | |||
This script can be used like this: | |||
{{Command | |||
|lang="R" | |||
| Rscript arguments_test.R Hello 42 | |||
|result= | |||
[1] "Processing with name:'Hello' and number:'42'" | |||
}} | |||
==Exploiting parallelism in R== <!--T:46--> | ==Exploiting parallelism in R== <!--T:46--> |