gpt4 book ai didi

r - R函数解析命令行参数

转载 作者:行者123 更新时间:2023-12-04 10:47:49 27 4
gpt4 key购买 nike

我下面有以下函数,用于解析命令行参数,以便可以从命令行运行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)
}

这是当我尝试使用以下命令行参数调用使用以上函数来解析CL参数的 R脚本时的CLI session 输出:
./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

帮助?

[[更新]]

我遵循了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))

当我运行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

???

最佳答案

我正在回答您的第二个问题,关于optparse遇到的错误:

make_option帮助页面(...):

action: A character string that describes the action optparse should take when it encounters an option, either “store”, “store_true”, or “store_false”. The default is "store” which signifies that optparse should store the specified following value if the option is found on the command string. “store_true” stores TRUE if the option is found and “store_false” stores FALSE if the option is found.



简而言之,如果要运行以下命令,则需要使用 action = "store"(默认设置):
./myscript.R --param1='XLIF' --param2='ESX' [...]

关于r - R函数解析命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11649222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com