programing

명령줄 인수를 RCMD BATCH에 전달하는 중

css3 2023. 6. 4. 22:27

명령줄 인수를 RCMD BATCH에 전달하는 중

사용해 왔습니다.R CMD BATCH my_script.R터미널에서 실행하기 위해R대본. 하고 싶지만 .지금은 명령에 인수를 전달하고 싶지만 실행하는 데 문제가 있습니다.내가 하면,R CMD BATCH my_script.R blabla그리고나서blabla실행 중인 R 스크립트에서 사용할 수 있는 인수로 해석되지 않고 출력 파일이 됩니다.

는 난시다했을 요.Rscript my_script.R blabla그것은 전해지는 것처럼 보입니다.blabla주장대로 옳지만, 그렇다면 이해할 수 없습니다.my_script.Rout▁file▁ 얻는 출력 파일.R CMD BATCH(나는 원합니다..Rout을 통의출력다리로디수션할있동안는렉음화으을로 수 있습니다.Rscript선택한 으로, R을 내가선택파이로으름, 포된함다명방니것않입을지해하을령나는일력 으로 받지 못할 입니다.R CMD BATCH에서 수행합니다..Rout 파일파.

저는, ▁the▁via▁▁to▁being▁executed▁so다▁r▁an,▁arguments니를 통해 실행되는 R 스크립트에 인수를 전달하는 .R CMD BATCH방법, 하지만 사용하는 접근법에 만족할 것입니다.Rscript유사한 것을 생산할 수 있는 방법이 있다면,.Routjava.

은 내인은입니다.R CMD BATCH약간의 유물입니다., 더최에근,▁more더에.Rscript 파일플랫폼에서 과 제공됩니다.commandArgs()명령줄 인수를 쉽게 처리할 수 있습니다.

를 들어, 스크립트가 . 를예들어, . --불보러은기요▁--."myScript.R":

## myScript.R
args <- commandArgs(trailingOnly = TRUE)
rnorm(n=as.numeric(args[1]), mean=as.numeric(args[2]))

명령행에서 호출하는 방법은 다음과 같습니다.

> Rscript myScript.R 5 100
[1]  98.46435 100.04626  99.44937  98.52910 100.78853

편집:

제가 권하고 싶은 건 아니지만...의조을사여하용의 조합을 source()그리고.sink()당신은 얻을 수 있습니다.Rscript를 제작하다.Rout에 의해 생산된 것과 같은 파일R CMD BATCH한 가지 방법은 작은 R 스크립트를 만드는 것입니다. -- 불러보세요. RscriptEcho.RRscript로 직접 호출합니다.다음과 같이 표시될 수 있습니다.

## RscriptEcho.R
args <- commandArgs(TRUE)
srcFile <- args[1]
outFile <- paste0(make.names(date()), ".Rout")
args <- args[-1]

sink(outFile, split = TRUE)
source(srcFile, echo = TRUE)

실제 스크립트를 실행하려면 다음을 수행합니다.

Rscript RscriptEcho.R myScript.R 5 100
[1]  98.46435 100.04626  99.44937  98.52910 100.78853

는 그은실것입다니될을 실행할 입니다.myScript.R와 싱크 및 를 고유 인 " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " " 을 사용합니다..Rout.

편집2:
Rscript를 상세하게 실행하고 상세한 출력을 파일에 저장할 수 있습니다.

Rscript --verbose myScript.R 5 100 > myScript.Rout

여기에 설명된 옵션을 사용해 본 후, 저는 R-블로거에 있는 Forester의 이 게시물을 발견했습니다.저는 그것이 고려해야 할 깨끗한 선택이라고 생각합니다.

그의 코드를 여기에 넣었습니다.

명령줄에서

$ R CMD BATCH --no-save --no-restore '--args a=1 b=c(2,5,6)' test.R test.out &

테스트 R

##First read in the arguments listed at the command line
args=(commandArgs(TRUE))

##args is now a list of character vectors
## First check to see if arguments are passed.
## Then cycle through each element of the list and evaluate the expressions.
if(length(args)==0){
    print("No arguments supplied.")
    ##supply default values
    a = 1
    b = c(1,1,1)
}else{
    for(i in 1:length(args)){
      eval(parse(text=args[[i]]))
    }
}

print(a*2)
print(b*3)

테스트 중.나가.

> print(a*2)
[1] 2
> print(b*3)
[1]  6 15 18

포레스터 덕분입니다!

앞에 .my_script.R 및사를 합니다.-예를 들어, 논쟁에서.

R CMD BATCH -blabla my_script.R

commandArgs()를 받을 것입니다.-blabla이 경우 문자열로 사용할 수 있습니다.자세한 내용은 도움말을 참조하십시오.

$ R CMD BATCH --help
Usage: R CMD BATCH [options] infile [outfile]

Run R non-interactively with input from infile and place output (stdout
and stderr) to another file.  If not given, the name of the output file
is the one of the input file, with a possible '.R' extension stripped,
and '.Rout' appended.

Options:
  -h, --help        print short help message and exit
  -v, --version     print version info and exit
  --no-timing           do not report the timings
  --            end processing of options

Further arguments starting with a '-' are considered as options as long
as '--' was not encountered, and are passed on to the R process, which
by default is started with '--restore --save --no-readline'.
See also help('BATCH') inside R.

스크립트에서 R 립트호된라고 합니다.test.R:

args <- commandArgs(trailingOnly = F)
myargument <- args[length(args)]
myargument <- sub("-","",myargument)
print(myargument)
q(save="no")

명령줄 실행에서 다음 작업을 수행합니다.

R CMD BATCH -4 test.R

출력 파일, 테스트.라우팅, 인수가 다음과 같이 표시됩니다.4R: 에 성공적으로 전달되었습니다.

cat test.Rout

> args <- commandArgs(trailingOnly = F)
> myargument <- args[length(args)]
> myargument <- sub("-","",myargument)
> print(myargument)
[1] "4"
> q(save="no")
> proc.time()
user  system elapsed 
0.222   0.022   0.236 

저는 한 줄 솔루션이 항상 좋다고 생각하기 때문에 답변을 추가합니다!당신의 맨 위에myRscript.R파일, 다음 행을 추가합니다.

eval(parse(text=paste(commandArgs(trailingOnly = TRUE), collapse=";")))

그런 다음 스크립트를 다음과 같이 제출합니다.

R CMD BATCH [options] '--args arguments you want to supply' myRscript.R &

예:

R CMD BATCH --vanilla '--args N=1 l=list(a=2, b="test") name="aname"' myscript.R &

그러면:

> ls()
[1] "N"    "l"    "name"

다음은 명령행 인수를 처리하는 다른 방법입니다.R CMD BATCH여기서 이전 답변을 기반으로 하는 제 접근 방식을 사용하면 명령줄에서 인수를 지정하고 R 스크립트에서 인수의 일부 또는 전부를 기본값으로 지정할 수 있습니다.

여기 R 파일이 있습니다.이름은 테스트입니다.R:

defaults <- list(a=1, b=c(1,1,1)) ## default values of any arguments we might pass

## parse each command arg, loading it into global environment
for (arg in commandArgs(TRUE))
  eval(parse(text=arg))

## if any variable named in defaults doesn't exist, then create it
## with value from defaults
for (nm in names(defaults))
  assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]))[[1]])

print(a)
print(b)

명령줄에서 다음과 같이 입력하면

R CMD BATCH --no-save --no-restore '--args a=2 b=c(2,5,6)' test.R

R R 면러서 R 리우는에가 있을 입니다.a=2그리고.b=c(2,5,6)하지만 전 생략할 수 있어요b 또 다 추 니 합 가 다 을 주 장 른c:

R CMD BATCH --no-save --no-restore '--args a=2 c="hello"' test.R

그러면 R에서 우리가a=2,b=c(1,1,1)및 (으)로 표시됩니다.c="hello".

마지막으로, 환경에 주의한다면 편의를 위해 R 코드를 함수로 묶을 수 있습니다.

## defaults should be either NULL or a named list
parseCommandArgs <- function(defaults=NULL, envir=globalenv()) {
  for (arg in commandArgs(TRUE))
    eval(parse(text=arg), envir=envir)

  for (nm in names(defaults))
    assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]), envir=envir)[[1]], pos=envir)
}

## example usage:
parseCommandArgs(list(a=1, b=c(1,1,1)))

언급URL : https://stackoverflow.com/questions/14167178/passing-command-line-arguments-to-r-cmd-batch