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.
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.
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.
Use commandArgs(trailingOnly = TRUE) to obtain a vector of the command-line arguments that a program was run with.
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.
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))
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