Search
Duplicate
🛠️

R에서 argument parsing 하기

Optparse 라이브러리를 이용한다.

설치

conda install -c bioconda r-optparse
Shell
복사

사용 방법

make_option 함수의 결과가 옵션이고, 그 결과들을 리스트로 저장해서 OptionParser를 initialize해주면 된다. OptionParser 객체에 parse_args (python argparse랑 똑같다!) 를 실행시키면 명령행 인자를 파싱한다.
library(optparse) option_list <- list( make_option(c("-f", "--file"), type="character", default=NULL, help="dataset file name", metavar="character"), make_option(c("-o", "--out"), type="character", default="out.txt", help="output file name [default= %default]", metavar="character") ) opt_parser <- OptionParser(option_list=option_list) opt <- parse_args(opt_parser)
Shell
복사

인자 타입에는 어떤게 있나?

type 에는 “logical”, “integer”, “double”, “complex”, or “character”를 넣을 수 있음.
action="store_true"action="store_false" 사용하면 boolean 값도 받을 수 있음.

필수 인자는 어떻게 나타냄?

조금 귀찮다. 파싱한 옵션 결과를 보고 그게 null인지 확인해서 null이면 stop으로 프로그램 실행을 끝내버리면 된다.
if (is.null(opt$file)) { print_help(opt_parser) stop("At least one argument must be supplied (input file).n", call.=FALSE) }
Shell
복사