无法通过 R 中的 getopt 包加载文件

Failed to load file through getopt package in R

我正在尝试使用 getopt 包打开我的文件,但代码似乎不起作用:

> library(getopt)
args <- commandArgs(trailingOnly = FALSE)

spec = matrix(c(
'help'   , 'h', 0, "character",
'input'  , 'i', 1, "file",
'output' , 'o', 1, "character"), byrow=TRUE, ncol=4)
opt = getopt(spec)
if(opt$input){
file <- read.table(args[1])
}
print(file)

我正在尝试使用命令行来 运行 像这样的代码:

Rscript --slave filename.R -i file.txt 

错误信息为: storage.mode(peek.optstring) <- 模式错误:无效值 调用:getopt ... tryCatch -> tryCatchList -> tryCatchOne -> doTryCatch 执行暂停 有人可以帮我吗?

您需要测试组件,如果给出了 -i filename.txt,那么 opt$file 就是您用来访问它的内容。

修复后的版本是

#!/usr/bin/Rscript

library(getopt)
spec <- matrix(c(
    'help'   , 'h', 0, "character",
    'input'  , 'i', 1, "character",
    'output' , 'o', 1, "character"),
    byrow=TRUE, ncol=4)
opt <- getopt(spec)

if ( !is.null(opt$input) ) {
    file <- read.table(opt$input)
}

print(file)

我以前经常使用这个包,但现在我更喜欢 docopt,它更容易使用,功能更强大。

万一其他人运行遇到同样的问题,我收到同样的错误信息

Error in getopt_options(object, args) : 
  Error in storage.mode(this.argument) <- mode : invalid value
Calls: parse_args -> parse_options -> getopt_options

我的错误原来是不小心拼错了我的类型参数:

make_option(c("--chr_len"), type = 'chaqracter', default = NULL, help = "file path: length of all chromosomes")

当我修正拼写后,这个错误就解决了

  make_option(c("--chr_len"), type = 'character', default = NULL, help = "file path: length of all chromosomes")