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

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.

Leave a Comment