R 스크립트에서 명령줄 매개 변수를 읽으려면 어떻게 해야 합니까?
코드 자체의 하드 코드 매개 변수 값이 아닌 여러 명령줄 매개 변수를 제공할 수 있는 R 스크립트가 있습니다.이 스크립트는 윈도우즈에서 실행됩니다.
명령줄에 제공된 매개 변수를 R 스크립트로 읽는 방법에 대한 정보를 찾을 수 없습니다.만약 그것이 불가능하다면 나는 놀랄 것입니다, 그래서 아마도 나는 내 구글 검색에서 최고의 키워드를 사용하지 않을 것입니다...
조언이나 추천 사항이 있습니까?
더크의 대답은 당신이 필요로 하는 모든 것입니다.여기 재현 가능한 최소한의 예가 있습니다.
두 개의 파일을 만들었습니다.exmpl.bat
그리고.exmpl.R
.
exmpl.bat
:set R_Script="C:\Program Files\R-3.0.2\bin\RScript.exe" %R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1
는사용또를
Rterm.exe
:set R_TERM="C:\Program Files\R-3.0.2\bin\i386\Rterm.exe" %R_TERM% --no-restore --no-save --args 2010-01-28 example 100 < exmpl.R > exmpl.batch 2>&1
exmpl.R
:options(echo=TRUE) # if you want see commands in output file args <- commandArgs(trailingOnly = TRUE) print(args) # trailingOnly=TRUE means that only your arguments are returned, check: # print(commandArgs(trailingOnly=FALSE)) start_date <- as.Date(args[1]) name <- args[2] n <- as.integer(args[3]) rm(args) # Some computations: x <- rnorm(n) png(paste(name,".png",sep="")) plot(start_date+(1L:n), x) dev.off() summary(x)
을 모두 동일한 하고 시작합니다.exmpl.bat
결과적으로 다음을 얻을 수를 얻을 수 있습니다.
example.png
exmpl.batch
것을 다
변수 환 변 수 있 다 니 습 도할을 .%R_Script%
:
"C:\Program Files\R-3.0.2\bin\RScript.exe"
에서 " 배스트립에다같사이용다니합음과"로 합니다.%R_Script% <filename.r> <arguments>
의 RScript
그리고.Rterm
:
Rscript
이 더 단순합니다.Rscript
x64에서 아키텍처를 자동으로 선택(자세한 내용은 R 설치 및 관리, 2.6 하위 아키텍처 참조)Rscript
요필이 합니다.options(echo=TRUE)
을 쓸 에 입력합니다.
몇 가지 요점:
변수는 령줄매개변다통액해수있다니습세를 통해 수 있습니다.
commandArgs()
자, 보세요help(commandArgs)
개괄적으로사용할 수 있습니다.
Rscript.exe
Windows를 포함한 모든 플랫폼에서 사용할 수 있습니다.은 지할것다니입원을 입니다.commandArgs()
Windows로 이식할 수 있는 파일은 거의 없지만 현재는 OS X와 Linux에서만 사용할 수 있습니다.CRAN에는 getopt와 optparse라는 두 가지 추가 패키지가 있으며, 이 두 패키지는 모두 명령줄 구문 분석을 위해 작성되었습니다.
2015년 11월 편집: 새로운 대안이 등장했고 진심으로 도콥트를 추천합니다.
스크립트의 맨 위에 추가합니다.
args<-commandArgs(TRUE)
은 그런다전인다수같음수있다로 전달된 할 수 .args[1]
,args[2]
그럼 실행
Rscript myscript.R arg1 arg2 arg3
인수가 공백이 있는 문자열인 경우 큰따옴표로 묶습니다.
때부터optparse
답변에서 여러 번 언급되었으며 명령행 처리를 위한 포괄적인 키트를 제공합니다. 입력 파일이 존재한다고 가정할 때 이 키트를 사용하는 방법에 대한 간략한 예는 다음과 같습니다.
script.R:
library(optparse)
option_list <- list(
make_option(c("-n", "--count_lines"), action="store_true", default=FALSE,
help="Count the line numbers [default]"),
make_option(c("-f", "--factor"), type="integer", default=3,
help="Multiply output by this number [default %default]")
)
parser <- OptionParser(usage="%prog [options] file", option_list=option_list)
args <- parse_args(parser, positional_arguments = 1)
opt <- args$options
file <- args$args
if(opt$count_lines) {
print(paste(length(readLines(file)) * opt$factor))
}
의 파일이 된 경우blah.txt
23줄로
명령줄에서:
Rscript script.R -h
산출물
Usage: script.R [options] file
Options:
-n, --count_lines
Count the line numbers [default]
-f FACTOR, --factor=FACTOR
Multiply output by this number [default 3]
-h, --help
Show this help message and exit
Rscript script.R -n blah.txt
산출물 [1] "69"
Rscript script.R -n -f 5 blah.txt
산출물 [1] "115"
도서관을 이용해 보세요... 더 좋은 일이 생기길 원한다면요.예:
spec <- matrix(c(
'in' , 'i', 1, "character", "file from fastq-stats -x (required)",
'gc' , 'g', 1, "character", "input gc content file (optional)",
'out' , 'o', 1, "character", "output filename (optional)",
'help' , 'h', 0, "logical", "this help"
),ncol=5,byrow=T)
opt = getopt(spec);
if (!is.null(opt$help) || is.null(opt$in)) {
cat(paste(getopt(spec, usage=T),"\n"));
q();
}
당신은 더 적게 필요합니다 ('little r'로 발음됨)
더크는 약 15분 후에 자세히 설명하기 위해 들를 것입니다;)
bash에서 다음과 같은 명령줄을 구성할 수 있습니다.
$ z=10
$ echo $z
10
$ Rscript -e "args<-commandArgs(TRUE);x=args[1]:args[2];x;mean(x);sd(x)" 1 $z
[1] 1 2 3 4 5 6 7 8 9 10
[1] 5.5
[1] 3.027650
$
당신은 그 변수를 볼 수 있습니다.$z
bash 셸에 "10"으로 대체되고 이 값은commandArgs
에게 먹인.args[2]
및 range 명령어x=1:10
R에 의해 성공적으로 실행되는 등.
참고로, R 함수의 인수를 검색하는 함수 args()가 있으며, args라는 인수 벡터와 혼동하지 않습니다.
플래그(예: -h, --help, --number=42 등)를 사용하여 옵션을 지정해야 하는 경우 R 패키지 optparse(Python에서 영감): http://cran.r-project.org/web/packages/optparse/vignettes/optparse.pdf 를 사용할 수 있습니다.
적어도 이것이 제가 당신의 질문을 이해하는 방법입니다. 왜냐하면 저는 bash getopt, perl Getopt, 또는 python argparse와 optparse와 동등한 것을 찾을 때 이 게시물을 발견했기 때문입니다.
저는 이 스위칭 동작을 생성하기 위해 훌륭한 데이터 구조와 처리 체인을 조합했을 뿐이며, 라이브러리는 필요하지 않습니다.몇 번이고 구현되었을 것이며, 사례를 찾아 이 스레드를 우연히 발견했습니다. 제가 칩을 넣으려고 생각했습니다.
특별히 플래그가 필요하지도 않았습니다(여기서 유일한 플래그는 다운스트림 기능을 시작하는 조건으로 확인하는 변수를 만드는 디버그 모드입니다).if (!exists(debug.mode)) {...} else {print(variables)})
플래그 검사lapply
아래의 문은 다음과 같습니다.
if ("--debug" %in% args) debug.mode <- T
if ("-h" %in% args || "--help" %in% args)
어디에args
명령행 인수(문자 벡터, 와 동일)에서 읽은 변수입니다.c('--debug','--help')
예를 들어, 당신이 이것들을 공급할 때)
다른 플래그에 재사용할 수 있으며 모든 반복을 피할 수 있으며 라이브러리가 없으므로 종속성이 없습니다.
args <- commandArgs(TRUE)
flag.details <- list(
"debug" = list(
def = "Print variables rather than executing function XYZ...",
flag = "--debug",
output = "debug.mode <- T"),
"help" = list(
def = "Display flag definitions",
flag = c("-h","--help"),
output = "cat(help.prompt)") )
flag.conditions <- lapply(flag.details, function(x) {
paste0(paste0('"',x$flag,'"'), sep = " %in% args", collapse = " || ")
})
flag.truth.table <- unlist(lapply(flag.conditions, function(x) {
if (eval(parse(text = x))) {
return(T)
} else return(F)
}))
help.prompts <- lapply(names(flag.truth.table), function(x){
# joins 2-space-separatated flags with a tab-space to the flag description
paste0(c(paste0(flag.details[x][[1]][['flag']], collapse=" "),
flag.details[x][[1]][['def']]), collapse="\t")
} )
help.prompt <- paste(c(unlist(help.prompts),''),collapse="\n\n")
# The following lines handle the flags, running the corresponding 'output' entry in flag.details for any supplied
flag.output <- unlist(lapply(names(flag.truth.table), function(x){
if (flag.truth.table[x]) return(flag.details[x][[1]][['output']])
}))
eval(parse(text = flag.output))
참고:flag.details
여기서 명령은 문자열로 저장되며, 다음으로 평가됩니다.eval(parse(text = '...'))
Optparse는 모든 심각한 스크립트에 적합하지만, 최소 기능 코드도 때때로 좋습니다.
샘플 출력:
Rscript check_mail.Rscript --도움말--Debug XYZ 함수를 실행하는 대신 변수를 인쇄합니다... -h --help 플래그 정의 표시
언급URL : https://stackoverflow.com/questions/2151212/how-can-i-read-command-line-parameters-from-an-r-script
'it-source' 카테고리의 다른 글
Angular 빌드에서 'es6'(또는 접미사가 전혀 없음)가 아닌 'es5'와 'es2015'로 파일을 만드는 이유는 무엇입니까? (0) | 2023.06.10 |
---|---|
GoogleSignIn, AdMob으로 인해 앱 제출 시 "앱이 사용 설명 없이 개인 정보에 민감한 데이터에 액세스 시도" iOS 10 GM 릴리스 오류 (0) | 2023.06.10 |
ASP.Net MVC 보기에서 컨트롤러로 데이터를 전달하는 방법 (0) | 2023.06.10 |
파이썬/판다를 사용하여 엑셀에서 색상 그라데이션을 만드는 가장 쉬운 방법은 무엇입니까? (0) | 2023.06.10 |
Python은 변수가 목록에 있는 어떤 유형의 인스턴스인지 확인합니다. (0) | 2023.06.10 |