Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass command-line arguments when calling source() on an R file within another R file

Tags:

r

In one R file, I plan to source another R file that supports reading two command-line arguments. This sounds like a trivial task but I couldn't find a solution online. Any help is appreciated.

like image 532
Leo5188 Avatar asked Jan 25 '13 16:01

Leo5188


People also ask

How do you pass a command line argument?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.

How can I call one R file from another?

You can execute R script as you would normally do by using the Windows command line. If your R version is different, then change the path to Rscript.exe. Use double quotes if the file path contains space.

How do I get command line arguments in R?

Use commandArgs(trailingOnly = TRUE) to obtain a vector of the command-line arguments that a program was run with.


2 Answers

I assume the sourced script accesses the command line arguments with commandArgs? If so, you can override commandArgs in the parent script to return what you want when it is called in the script you're sourcing. To see how this would work:

file_to_source.R

print(commandArgs()) 

main_script.R

commandArgs <- function(...) 1:3 source('file_to_source.R') 

outputs [1] 1 2 3

If your main script doesn't take any command line arguments itself, you could also just supply the arguments to this script instead.

like image 181
Matthew Plourde Avatar answered Sep 20 '22 23:09

Matthew Plourde


The simplest solution is to replace source() with system() and paste. Try

arg1 <- 1 arg2 <- 2 system(paste("Rscript file_to_source.R", arg1, arg2)) 
like image 29
canary_in_the_data_mine Avatar answered Sep 22 '22 23:09

canary_in_the_data_mine