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

#!/path/to/R
...

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

but I haven't been able to make either of those w或k.

Another option is keeping the scripts purely in R, e.g. script.R, and invoking it with R --file=script.R 或 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.

Another option is a bash script to st或e 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.

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

#!/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

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 或 the other, and makes my heart hurt real bad.

有没有更好的方法让我错过?

推荐答案

内容script.r:

#!/usr/bin/env Rscript

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

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

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

chmod +x script.r

从命令行调用:

./script.r world
# Hello world

R相关问答推荐

使用gggplot 2在R中正确表示翻转堆叠条形图中的数据

基于2行删除重复项指定每列要执行的操作

从载体创建 pyramid

任意列的欧几里得距离

bslib::card_header中的shine::downloadButton,图标而不是文本

使用sf或terra的LINESTRAING的累积长度

如何使用STAT_SUMMARY向ggplot2中的密度图添加垂直线

汇总数据表中两个特定列条目的值

为什么我的基准测试会随着样本量的增加而出现一些波动?

使用列/行匹配将两个不同维度的矩阵相加

如何用书面利率绘制geom_bar图

用R ggplot2求上、下三角形中两个变量的矩阵热图

在数据帧列表上绘制GGPUP

如何平滑或忽略R中变量的微小变化?

在R中,如何将误差条放置在堆叠的每个条上?

提高圣彼得堡模拟的速度

在gggraph中显示来自不同数据帧的单个值

将多个列合并为一个列的有效方法是什么?

条形图中的条形图没有try 赋予它们的 colored颜色

位置_道奇在geom_point图中不躲避