我在下面有以下函数,我用它来解析命令行参数,以便我可以从命令行运行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)
}
Run Code Online (Sandbox Code Playgroud)
当我尝试R使用以下命令行参数调用使用上述函数解析CL参数的脚本时,这是一个CLI会话输出:
./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
Run Code Online (Sandbox Code Playgroud)
救命?
[[更新]]
我遵循了Dirk的建议并安装了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))
Run Code Online (Sandbox Code Playgroud)
当我运行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
Run Code Online (Sandbox Code Playgroud)
???
我正在回答您的第二个问题,关于您遇到的错误optparse:
从make_option帮助页面(...):
\n\n\naction:描述 optparse 在遇到选项时应采取的操作的字符串,可以是 \xe2\x80\x9cstore\xe2\x80\x9d、\xe2\x80\x9cstore_true\xe2\x80\x9d 或 \xe2\x80 \x9cstore_false\xe2\x80\x9d。默认值为“store\xe2\x80\x9d”,这表示如果在命令字符串中找到该选项,optparse 应存储指定的以下值。如果找到该选项,\xe2\x80\x9cstore_true\xe2\x80\x9d 存储 TRUE如果找到该选项,则 \xe2\x80\x9cstore_false\xe2\x80\x9d 存储 FALSE。
\n
简而言之,action = "store"如果您想运行类似以下内容,则需要使用(默认):
./myscript.R --param1=\'XLIF\' --param2=\'ESX\' [...]\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2859 次 |
| 最近记录: |