コマンドラインオプションを説明する方法は、ほとんどの人がそれらが使用されることを期待する方法とは異なります。通常、コマンドラインオプションは単一のパラメーターを取り、先行するオプションのないパラメーターは引数として渡されます。引数が複数の項目(ファイルのリストなど)を取る場合は、strsplit()を使用して文字列を解析することをお勧めします。
optparseを使用した例を次に示します。
library (optparse)
option_list <- list ( make_option (c("-f","--filelist"),default="blah.txt",
help="comma separated list of files (default %default)")
)
parser <-OptionParser(option_list=option_list)
arguments <- parse_args (parser, positional_arguments=TRUE)
opt <- arguments$options
args <- arguments$args
myfilelist <- strsplit(opt$filelist, ",")
print (myfilelist)
print (args)
いくつかの実行例を次に示します。
$ Rscript blah.r -h
Usage: blah.r [options]
Options:
-f FILELIST, --filelist=FILELIST
comma separated list of files (default blah.txt)
-h, --help
Show this help message and exit
$ Rscript blah.r -f hello.txt
[[1]]
[1] "hello.txt"
character(0)
$ Rscript blah.r -f hello.txt world.txt
[[1]]
[1] "hello.txt"
[1] "world.txt"
$ Rscript blah.r -f hello.txt,world.txt another_argument and_another
[[1]]
[1] "hello.txt" "world.txt"
[1] "another_argument" "and_another"
$ Rscript blah.r an_argument -f hello.txt,world.txt,blah another_argument and_another
[[1]]
[1] "hello.txt" "world.txt" "blah"
[1] "an_argument" "another_argument" "and_another"
strsplitの場合、正規表現を使用して区切り文字を決定できることに注意してください。次のようなものをお勧めします。これにより、コンマまたはコロンを使用してリストを区切ることができます。
myfilelist <- strsplit (opt$filelist,"[,:]")