optparse NA缺省值不会被命令行参数覆盖

问题描述 投票:0回答:1

请考虑以下脚本:

library(optparse)

option_list <- list(
    make_option(c('--sample_p'), default=NA, dest='sample_p', help='Sample probability of inclusion if randomly sampling records')
)

args <- parse_args(OptionParser(option_list=option_list))
print(args)

if(!is.na(args$sample_p)){
    print('Chose to sample')
}else{
    print('Did not choose to sample')
}

我想将浮点值传递给脚本,以存储在args$sample_p中。我已经尝试了以下方法,但是两种方法都无法保存0.05

$ Rscript test.R --sample_p 0.05
$sample_p
[1] NA

$help
[1] FALSE

[1] "Did not choose to sample"
$ Rscript test.R --sample_p=0.05
Warning message:
In getopt(spec = spec, opt = args) :
  long flag sample_p given a bad argument
$sample_p
[1] NA

$help
[1] FALSE

[1] "Did not choose to sample"

但是,如果我将sample_p的默认值更改为数字,而不是NA,它会起作用:

library(optparse)

option_list <- list(
    make_option(c('--sample_p'), default=0, dest='sample_p', help='Sample probability of inclusion if randomly sampling records')
)

args <- parse_args(OptionParser(option_list=option_list))
print(args)

if(!is.na(args$sample_p)){
    print('Chose to sample')
}else{
    print('Did not choose to sample')
}
$ Rscript test.R --sample_p 0.05
$sample_p
[1] 0.05

$help
[1] FALSE

[1] "Chose to sample"

为什么NA作为默认值会引起问题?

r command-line-arguments
1个回答
0
投票

看起来您需要使用NA_real_来指定要在此上下文中使用的NA的类型(https://stat.ethz.ch/R-manual/R-devel/library/base/html/NA.html)。

option_list <- list(
    make_option(c('--sample_p'), default=NA_real_, dest='sample_p', help='Sample probability of inclusion if randomly sampling records')
)
© www.soinside.com 2019 - 2024. All rights reserved.