R语言命令行执行代码的3种方式(传递参数和环境变量)
大部分情况在IDE环境中运行R程序,但有时也需要在shell中运行,和其他语言的脚本一样。在shell中如何运行R语言的代码呢?
为了简化使用,把R/Rscript的可执行路径加入path环境变量。(bash,windows cmd)
使用R
首先看看R的help
c:\R> R --arch x64 --help
Usage: Rterm [options] [< infile] [> outfile] [EnvVars]
Start R, a system for statistical computation and graphics, with the
specified options
EnvVars: Environmental variables can be set by NAME=value strings
Options:
-h, --help Print usage message and exit
--version Print version info and exit
--encoding=enc Specify encoding to be used for stdin
--encoding enc ditto
--save Do save workspace at the end of the session
--no-save Don't save it
--no-environ Don't read the site and user environment files
--no-site-file Don't read the site-wide Rprofile
--no-init-file Don't read the .Rprofile or ~/.Rprofile files
--restore Do restore previously saved objects at startup
--no-restore-data Don't restore previously saved objects
--no-restore-history Don't restore the R history file
--no-restore Don't restore anything
--workspace=file Workspace to be restored
--vanilla Combine --no-save, --no-restore, --no-site-file,
--no-init-file and --no-environ
--max-mem-size=N Set limit for memory to be used by R
--max-ppsize=N Set max size of protect stack to N
-q, --quiet Don't print startup message
--silent Same as --quiet
--no-echo Make R run as quietly as possible
--verbose Print more information about progress
--args Skip the rest of the command line
--ess Don't use getline for command-line editing
and assert interactive use
-f file Take input from 'file'
--file=file ditto
-e expression Use 'expression' as input
One or more -e options can be used, but not together with -f or --file
An argument ending in .RData (in any case) is taken as the path
to the workspace to be restored (and implies --restore)
由此可见,R可以接受输入重定向的文件内容,可以通过-f file
或--file=file
指定文件输入。
有一个选项--args
可以提示R跳过之后的参数,其实后面的参数作为传递给R进程。脚本中的
commandArgs()
函数可以捕获命令行输入的所有参数。其中,trailingOnly = TRUE
只获得–args之后的参数。
命令行还可以定义NAME=value
形式的环境变量。环境变量的设置和--agrs
无关。
举个栗子: (简单起见,增加--vanilla --no-echo
参数)
demo.R内容
cat("\n")
cat("commandArgs(trailingOnly = FALSE)\n")
(args1<-commandArgs(trailingOnly = FALSE))
cat("\n")
cat("commandArgs(trailingOnly = TRUE)\n")
(args2<-commandArgs(trailingOnly = TRUE))
cat("\n")
cat("get environment variable\n")
Sys.getenv("AAA")
Sys.getenv("BBB")
命令:
R --vanilla --no-echo -f demo.R BBB=hehe --args AAA=haha
结果:
commandArgs(trailingOnly = FALSE)
[1] "C:\\PROGRA~1\\R\\R-40~1.3/bin/x64/Rterm.exe"
[2] "--vanilla"
[3] "--no-echo"
[4] "-f"
[5] "demo.R"
[6] "BBB=hehe"
[7] "--args"
[8] "AAA=haha"
commandArgs(trailingOnly = TRUE)
[1] "AAA=haha"
get environment variable
[1] "haha"
[1] "hehe"
使用Rscript
先看看Rscript的帮助:
Usage: /path/to/Rscript [--options] [-e expr [-e expr2 ...] | file] [args]
--options accepted are
--help Print usage and exit
--version Print version and exit
--verbose Print information on progress
--default-packages=list
Where 'list' is a comma-separated set
of package names, or 'NULL'
or options to R, in addition to --no-echo --no-restore, such as
--save Do save workspace at the end of the session
--no-environ Don't read the site and user environment files
--no-site-file Don't read the site-wide Rprofile
--no-init-file Don't read the user R profile
--restore Do restore previously saved objects at startup
--vanilla Combine --no-save, --no-restore, --no-site-file
--no-init-file and --no-environ
'file' may contain spaces but not shell metacharacters
Expressions (one or more '-e <expr>') may be used *instead* of 'file'
See also ?Rscript from within R
RScript其实R的简化版本,预定义了--no-echo --no-restore -f 和 --args
参数。
c:\R>Rscript demo.R BBB=hehe --args AAA=haha
commandArgs(trailingOnly = FALSE)
[1] "C:\\PROGRA~1\\R\\R-40~1.3\\bin\\x64\\Rterm.exe"
[2] "--no-echo"
[3] "--no-restore"
[4] "--file=demo.R"
[5] "--args"
[6] "BBB=hehe"
[7] "--args"
[8] "AAA=haha"
commandArgs(trailingOnly = TRUE)
[1] "BBB=hehe" "--args" "AAA=haha"
get environment variable
[1] "haha"
[1] "hehe"
使用R CMD BATCH
c:\R>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'.
Report bugs at <https://bugs.R-project.org>.
R CMD BATCH
似乎只能接受输入文件和输出文件,而且默认是--restore --save
的参数。
c:\R>R CMD BATCH --no-echo --encoding="UTF-8" demo.R demo.out --args AAA=haha
没有输出,打开文件demo.out,文件内容是:
commandArgs(trailingOnly = FALSE)
[1] "C:\\PROGRA~1\\R\\R-40~1.3/bin/x64/Rterm.exe"
[2] "-f"
[3] "demo.R"
[4] "--restore"
[5] "--save"
[6] "--no-echo"
[7] "--encoding=UTF-8"
commandArgs(trailingOnly = TRUE)
character(0)
get environment variable
[1] ""
[1] ""
> proc.time()
用户 系统 流逝
0.15 0.04 0.18
由此可见,R CMD BATCH file
不能给file传递参数,也不能传递环境变量。