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

前端 未结 5 1221
盖世英雄少女心
盖世英雄少女心 2020-11-29 20:33

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

5条回答
  •  臣服心动
    2020-11-29 21:06

    This works:

    # source another script with arguments
    source_with_args <- function(file, ...){
      commandArgs <<- function(trailingOnly){
        list(...)
      }
      source(file)
    }
    
    source_with_args("sourcefile.R", "first_argument", "second_argument")
    

    Note that the built in commandArgs function has to be redefined with <<- instead of <-. As I understand it, this makes its scope extend beyond the function source_with_args() where it is defined.

提交回复
热议问题