在命令行(终端)上使用 R 脚本的最佳方式是什么? [英] What's the best way to use R scripts on the command line (terminal)?

查看:30
本文介绍了在命令行(终端)上使用 R 脚本的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 R 脚本从命令行进行简单绘图非常方便.但是,从 bash 脚本运行 R 一点也不方便.理想的可能是这样的

It's very convenient to have R scripts for doing simple plots from the command line. However, running R from bash scripts is not convenient at all. The ideal might be something like

#!/path/to/R
...

#!/usr/bin/env R
...

但我无法完成其中任何一项.

but I haven't been able to make either of those work.

另一种选择是将脚本完全保留在 R 中,例如script.R,并使用 R --file=script.R 或类似方法调用它.然而,有时脚本会依赖于晦涩的命令行开关,此时部分代码存在于脚本之外.示例:通过本地 .Rprofile 将东西从 bash 潜入 R,所需的开关就是 --vanilla 暗示的一切,除了 --no-init-file.

Another option is keeping the scripts purely in R, e.g. script.R, and invoking it with R --file=script.R or similar. However, occasionally a script will rely on obscure command line switches at which point part of the code exists outside the script. Example: sneaking things into R from bash via a local .Rprofile, the desired switches are then everything --vanilla implies except --no-init-file.

另一个选项是 bash 脚本,用于存储 R 标志并可以轻松执行,然后调用 R 脚本.问题是这意味着单个程序被拆分成两个文件,现在必须保持同步,一起转移到新机器上,等等.

Another option is a bash script to store the R flags and be painlessly executable, which then calls the R script. The problem is that this means a single program just got split into two files which now have to be keep in sync, transferred to new machines together, etc.

我目前最不喜欢的选项是将 R 嵌入到 bash 脚本中:

The option I currently despise least is embedding the R in a bash script:

#!/bin/bash
... # usage message to catch bad input without invoking R
... # any bash pre-processing of input
... # etc
R --random-flags <<RSCRIPT
# R code goes here
RSCRIPT

所有内容都在一个文件中.它是可执行的并且可以轻松处理参数.问题是,像这样将 bash 和 R 结合起来几乎消除了任何 IDE 不会在其中一个或另一个上失败的可能性,这让我的心真的很痛.

Everything's in a single file. It's executable and easily handles arguments. The problem is that combining bash and R like this pretty much eliminates the possibility of any IDE not failing on one or the other, and makes my heart hurt real bad.

有没有更好的方法让我想念?

Is there some better way I'm missing?

推荐答案

script.r 的内容:

#!/usr/bin/env Rscript

args = commandArgs(trailingOnly = TRUE)
message(sprintf("Hello %s", args[1L]))

第一行是 shebang 行.最好的做法是使用 /usr/bin/env Rscript 而不是硬编码 R 安装路径.否则,您的脚本可能会在其他计算机上被破坏.

The first line is the shebang line. It’s best practice to use /usr/bin/env Rscript instead of hard-coding the path to your R installation. Otherwise you risk your script breaking on other computers.

接下来,使其可执行(在命令行上):

Next, make it executable (on the command line):

chmod +x script.r

从命令行调用:

./script.r world
# Hello world

这篇关于在命令行(终端)上使用 R 脚本的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆