LoginSignup
1
1

More than 5 years have passed since last update.

Rで起動引数のパース

Last updated at Posted at 2014-01-10

Rでunixぽい起動引数のパースしてくれるライブラリoptparseのメモ。
殆ど、Pythonの同名ライブラリと同じ使い方。

スクリプト本体

optparse.r
#!/usr/bin/env Rscript




library(optparse)




## make_optionでオプションの詳細を記述。それをリストにまとめる。
## オプションの記述方法は、Pythonのoptparseライブラリと殆ど同じ。
optslist <- list(
    make_option("--flag1",
                action="store_true",
                default=FALSE, 
                help="A Flag"), 
    make_option(c("-f", "--flag2"),
                action="store",
                default=FALSE,
                type="logical",
                help="A Flag"),
    make_option("--num",
                type="integer",
                default=1,
                help="A Number"),
    make_option("--raw-data",
                type="character",
                default="piyo",
                help="a string")
    )
parser <- OptionParser(option_list=optslist)
opts <- parse_args(parser)




## parse_argsで、起動引数の内容を含んだリストが取得出来る。
cat(sprintf("flag1=%s
flag2=%s
num=%d
raw-data=%s
",
            opts$flag1,
            opts$flag2,
            opts$num,
            opts[["raw-data"]]))




## 明示的にヘルプメッセージを出したい場合は、print_help
cat("\n\n\n--- help message ---\n")
print_help(parser)

出力

bash-3.2$ ./optparse.r --flag1 --num=101 --raw-data=foobar
flag1=TRUE
flag2=FALSE
num=101
raw-data=foobar



--- help message ---
Usage: ./optparse.r [options]


Options:
    --flag1
        A Flag

    -f FLAG2, --flag2=FLAG2
        A Flag

    --num=NUM
        A Number

    --raw-data=RAW-DATA
        a string

    -h, --help
        Show this help message and exit



1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1