是否可以在命令行中将代码传递给R或Rscript?

时间:2017-03-21 14:22:47

标签: r command-line

例如,test.R是一行文件:

$ cat test.R  
# print('Hello, world!')

我们可以Rscript test.RR CMD BATCH test.R运行此文件。但是,是否可以指示R执行通过管道传输的代码,例如cat test.R | Rscriptcat test.R | R CMD BATCH(两者都不起作用)?

1 个答案:

答案 0 :(得分:3)

Rscript不会听stdin:

$ echo "2 + 2" | 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 --slave --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
$

但是,littler一直这样做很好,因为它是为此建立的(以及更多):

$ echo "2 + 2" | r -p                # -p switch needed for print
[1] 4
$ echo "print(2 + 2)" | r 
[1] 4
$ 

请注意默认情况下操作&#34;无声&#34;明确的print()语句或-p标志都是你的朋友。

为了完整起见,R现在也可以这样做,但我忘记了它的添加时间:

$ echo "2 + 2" | R --slave
[1] 4
$ 

我有一个older blog post comparing the start-up speeds,所以我的钱仍然用于这些事情 - 我有很多脚本和cron工作使用它,因为它只是工作&#34;。