请考虑以下脚本:
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
作为默认值会引起问题?
看起来您需要使用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')
)