在命令行中是否可以将代码导入R或Rscript?

4
例如,test.R 是一个只有一行代码的文件。
$ cat test.R  
# print('Hello, world!')

我们可以通过 Rscript test.R 或者 R CMD BATCH test.R 来运行这个文件。但是,是否有可能让 R 执行通过管道传递过来的代码,例如 cat test.R | Rscript 或者 cat test.R | R CMD BATCH(两者都不起作用)?

1个回答

9

R脚本不会监听标准输入:

$ 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
$ 

请注意,默认情况下操作是“无声”的,除非使用显式的 print() 语句或 -p 标志。为了完整起见,R 现在也可以做到这一点,但我忘记了这是何时添加的。
$ echo "2 + 2" | R --slave
[1] 4
$ 

我有一篇 比较启动速度的旧博客文章,所以我的钱还是放在littler上,因为它非常适合这些事情——我有很多脚本和定时任务都使用它,因为它“只是有效”。


我在R中安装了你的littler包,并使用aliasr添加到我的~/.bashrc中。它运行得很好! - mt1022
出于好奇,通过别名?从已安装的软件包获取二进制文件?我通常只是将其软链接到“/usr/local/bin”。 - Dirk Eddelbuettel
默认情况下,该软件包安装在 ~/R/x86_64-pc-linux-gnu-library/3.3/littler/bin/r。如果我们没有在 /usr/local/bin 中的写入权限,我认为更容易更改 .bashrc - mt1022
没错。如果您不能使用sudo,那么很遗憾,这就是您所能得到的全部。 - Dirk Eddelbuettel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接