[英]How to pass command-line arguments when calling source() on an R file within another R file
在一個 R 文件中,我計划獲取另一個支持讀取兩個命令行 arguments 的 R 文件。這聽起來像是一項微不足道的任務,但我無法在網上找到解決方案。 任何幫助表示贊賞。
我假設源腳本使用commandArgs
訪問命令行參數? 如果是這樣,您可以覆蓋父腳本中的commandArgs
以在您正在采購的腳本中調用它時返回您想要的內容。 看看這將如何工作:
file_to_source.R
print(commandArgs())
main_script.R
commandArgs <- function(...) 1:3
source('file_to_source.R')
輸出[1] 1 2 3
如果您的主腳本本身不接受任何命令行參數,您也可以只向該腳本提供參數。
最簡單的解決方案是用system()
和paste
替換source()
。 嘗試
arg1 <- 1
arg2 <- 2
system(paste("Rscript file_to_source.R", arg1, arg2))
如果您有一個腳本源自另一個腳本,您可以在第一個腳本中定義可由源腳本使用的變量。
> tmpfile <- tempfile()
> cat("print(a)", file=tmpfile)
> a <- 5
> source(tmpfile)
[1] 5
@Matthew Plourde 答案的擴展版本。 我通常做的是使用 if 語句來檢查命令行參數是否已定義,否則讀取它們。
此外,我嘗試使用 argparse 庫來讀取命令行參數,因為它提供了更整潔的語法和更好的文檔。
要獲取的文件
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()
}
print (args)
文件調用源()
args$arg1 = "c"
args$arg2 = "d"
source ("file_to_be_sourced.R")
c, d
這有效:
# 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")
請注意,必須使用<<-
而不是<-
重新定義內置的commandArgs
函數。 據我了解,這使其范圍超出了定義它的函數source_with_args()
。
我在這里測試了一些替代方案,最后得到的是:
文件調用來源:
source_with_args <- function(file, ...){
system(paste("Rscript", file, ...))
}
source_with_args(
script_file,
paste0("--data=", data_processed_file),
paste0("--output=", output_file)
)
要獲取的文件:
library(optparse)
option_list = list(
make_option(
c("--data"),
type="character",
default=NULL,
help="input file",
metavar="filename"
),
make_option(
c("--output"),
type="character",
default=NULL,
help="output file [default= %default]",
metavar="filename"
)
)
opt_parser = OptionParser(option_list=option_list)
data_processed_file <- opt$data
oputput_file <- opt$output
if(is.null(data_processed_file) || is.null(oputput_file)){
stop("Required information is missing")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.