Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将命令行参数传递给R CMD批处理_R_Rscript - Fatal编程技术网

将命令行参数传递给R CMD批处理

将命令行参数传递给R CMD批处理,r,rscript,R,Rscript,我一直在从终端使用R CMD BATCH my_script.R执行R脚本。我现在想把一个参数传递给命令,但在让它工作时遇到了一些问题。如果执行R CMD批处理my_script.R blabla,则blabla将成为输出文件,而不是解释为正在执行的R脚本可用的参数 我尝试了Rscript my_script.R blabla,它似乎作为参数正确地传递了blabla,但是我没有得到my_script.Rout输出文件,我需要R CMD BATCH(我想要.Rout文件)。虽然我可以将对Rscri

我一直在从终端使用
R CMD BATCH my_script.R
执行
R
脚本。我现在想把一个参数传递给命令,但在让它工作时遇到了一些问题。如果执行
R CMD批处理my_script.R blabla
,则
blabla
将成为输出文件,而不是解释为正在执行的R脚本可用的参数

我尝试了
Rscript my_script.R blabla
,它似乎作为参数正确地传递了
blabla
,但是我没有得到
my_script.Rout
输出文件,我需要
R CMD BATCH
(我想要
.Rout
文件)。虽然我可以将对
Rscript
的调用的输出重定向到我选择的文件名,但我不会像
R CMD BATCH
.Rout
文件中那样获取文件中包含的R输入命令


理想情况下,我想通过
R CMD BATCH
方法将参数传递给正在执行的R脚本,如果有一种方法可以使它生成一个可比较的
.Rout
文件,那么我很乐意使用
Rscript
方法。

您需要在
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 CMD BATCH
有点残余。在任何情况下,最新的
Rscript
可执行文件(可在所有平台上使用)以及
commandArgs()
都使处理命令行参数变得非常简单

举个例子,这里有一个小脚本——称之为“myScript.R”:


编辑:

不是我推荐的,但是。。。使用
source()
sink()
的组合,您可以获得
Rscript
来生成一个
.Rout
文件,就像
R CMD BATCH
生成的文件一样。一种方法是创建一个小的R脚本——调用它
Rscript echo.R
——您可以使用Rscript直接调用它。可能是这样的:

## 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)
它将使用提供的参数执行
myScript.R
,并将交叉输入、输出和消息接收到唯一命名的
.Rout

Edit2:
您可以详细运行Rscript,并将详细输出放在文件中

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

在R脚本中,称为
test.R

## myScript.R
args <- commandArgs(trailingOnly = TRUE)
rnorm(n=as.numeric(args[1]), mean=as.numeric(args[2]))
args <- commandArgs(trailingOnly = F)
myargument <- args[length(args)]
myargument <- sub("-","",myargument)
print(myargument)
q(save="no")
您的输出文件test.Rout将显示参数
4
已成功传递给R:

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 
cat测试路由
>args myargument myargument打印(myargument)
[1] "4"
>q(保存=“否”)
>过程时间()
用户系统运行时间
0.222   0.022   0.236 

尝试了这里描述的选项后,我在r-bloggers中找到了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

谢谢你

我添加了一个答案,因为我认为单线解决方案总是好的! 在
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 &
然后:


下面是处理命令行参数的另一种方法,使用
R CMD BATCH
。我的方法基于此,允许您在命令行中指定参数,并在R脚本中指定部分或全部默认值

这是一个R文件,我将其命名为test.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中我们将有
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)))
##默认值应为NULL或命名列表

parseCommandArgs我注意到如果我这样做,并且在脚本中使用
args,您必须从末尾开始计算参数(例如,size-2,size-1,size)-您的参数将始终位于末尾。我还得到了这样的印象
R CMD BATCH
是一个遗迹。不过,我喜欢它的一点是,它生成了一个
.Rout
文件,该文件不仅包含脚本输出,还交错了生成该输出的
.R
脚本文件中的输入命令/注释。我听到了。这是(我想仍然是!)一个很好的
R CMD BATCH
。但是我认为你可以用
knitr
做得比
R CMD BATCH
更好,例如
Rscript-e“knitr::stitch(commandArgs(TRUE)[1])”我的脚本.R
(您可以用
stitch\u rhtml
stitch\u rmd
替换
stitch
,并且您需要从安装
knitr
,因为我刚刚在
stitch
中发现一个错误。)只需添加我的0.02,就可以很容易地从终端使用重定向。例如
Rscript myfile.R>path/to/mylog.Rout
,文件的输出保存在
.Rout
文件中,而不是打印到stdout(屏幕)。要添加到@JamesPringle,我通常希望我的输出都打印在屏幕上(实时监控)和文件(稍后查看).I do
Rscript myfile.R|tee mylog.Rout
需要注意的重要一点是,如果参数是字符类型,则不需要使用单引号/双引号。例如:R CMD BATCH'-args a=FolderName'test.R test.out&如Forester的帖子中所述,
-args
是键。它还可以与
R--no save--no restore--args a=1
R--no save--no restore
是否有方法将参数从命令行传递到--args?
> ls()
[1] "N"    "l"    "name"
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 CMD BATCH --no-save --no-restore '--args a=2 c="hello"' test.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)))