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

前端 未结 5 1217
盖世英雄少女心
盖世英雄少女心 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 20:50

    An extended version of @Matthew Plourde's answer. What I usually do is to have an if statement to check if the command line arguments have been defined, and read them otherwise.

    In addition I try to use the argparse library to read command line arguments, as it provides a tidier syntax and better documentation.

    file to be sourced

     if (!exists("args")) {
             suppressPackageStartupMessages(library("argparse"))
             parser <- ArgumentParser()
             parser$add_argument("-a", "--arg1", type="character", defalt="a",
                   help="First parameter [default %(defult)s]")
             parser$add_argument("-b", "--arg2", type="character", defalt="b",
                   help="Second parameter [default %(defult)s]")
             args <- parser$parse_args()
     }
    

    file calling source()

    args$arg1 = "c" 
    args$arg2 = "d"
    source ("file_to_be_sourced.R")
    print (args)
    

    c, d

提交回复
热议问题