2012-07-25 62 views
6

我具有低於下面的函數,其中我使用解析命令行參數,這樣我可以運行在命令行R腳本:一個R函數來解析命令行參數

parseArguments <- function() { 
    text1 <- commandArgs(TRUE) 
    eval(parse(text=gsub("\\s", ";", gsub("--","", text1)))) 
    args <- list() 
    for(ar in ls()[! ls() %in% c("text1", "args")]) {args[ar] <- get(ar)} 
    return (args) 
} 

這裏是一個CLI會話輸出,當我試圖調用R腳本,使用上面的函數解析CL參數,使用以下命令行參數:

./myscript.R --param1='XLIF' --param2='ESX' --param3=5650.0 --param4=5499.2 --param5=0.0027397260274 --param6='Jul' --riskfreerate=0.817284313119 --datafile='/path/to/some/datafile.csv' --imagedir='/path/to/images' --param7=2012 --param8=2 
Error in parse(text = gsub("\\s", ";", gsub("--", "", text1))) : 
    8:10: unexpected '/' 
7: riskfreerate=0.817284313119 
8: datafile=/ 
      ^
Calls: parseArguments -> eval -> parse 
Execution halted 

幫助?

[更新]

我跟了德克的意見,並安裝了optparse庫。我的代碼現在看起來像這樣:

library(optparse) 

# Get the parameters 
option_list <- list(
    make_option(c("-m", "--param1"), action="store_false"), 
    make_option(c("-t", "--param2"), action="store_false"), 
    make_option(c("-a", "--param3"), action="store_false"), 
    make_option(c("-s", "--param4"), action="store_false"), 
    make_option(c("-x", "--param5"), action="store_false"), 
    make_option(c("-o", "--param6"), action="store_false"), 
    make_option(c("-y", "--param7"), action="store_false"), 
    make_option(c("-r", "--riskfreerate"), action="store_false"), 
    make_option(c("-c", "--param8"), action="store_false"), 
    make_option(c("-d", "--datafile"), action="store_false"), 
    make_option(c("-i", "--imagedir"), action="store_false") 
) 

# get command line options, i 
opt <- parse_args(OptionParser(option_list=option_list)) 

當我運行將R腳本傳遞相同的命令行參數,我得到:

Loading required package: methods 
Loading required package: getopt 
Error in getopt(spec = spec, opt = args) : 
    long flag "param1" accepts no arguments 
Calls: parse_args -> getopt 
Execution halted 

???

回答

3

我回答你的第二個問題,有關錯誤你optparse遇到:

make_option幫助頁面(...):

行動:描述行動optparse的字符串在遇到選項時應採取「store」,「store_true」或「store_false」。缺省值爲「存儲」,表示如果在命令字符串中找到該選項,則optparse應存儲指定的下列值:「store_true」如果找到該選項則存儲TRUE,如果找到該選項,則存儲「FALSE」

總之,你需要使用action = "store"(默認值),如果你想運行類似:

./myscript.R --param1='XLIF' --param2='ESX' [...] 
7

是的,有CRAN包getoptoptparse只是爲此。

+0

+1的鏈接 – 2012-07-25 12:30:26

+0

請參閱我的更新問題(使用optparse) – 2012-07-25 13:00:46