使用bash脚本运行R命令

7
我有以下命令用于在R中制作图形。主要的文本文件是cross_correlation.csv。
如何将它放入bash脚本中,以便当我在终端上启动它时,R命令会执行其工作并完成(就像所有其他shell脚本一样)。
cross_correlation <- read.table(file.choose(), header=F, sep="\t")

barplot(cross_correlation$V3)
dev.copy(png,"cc.png",width=8,height=6,units="in",res=100)
dev.off()

hist(cross_correlation$V3, breaks=15, prob=T)
dev.copy(png,"hist_cc.png",width=8,height=6,units="in",res=100)
dev.off()

2
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Tim Biegeleisen
我正要建议使用 R CMD BATCH script.r,所以在我看来这是一个重复的问题。 - RHertel
最好有类似于“python -c'<commands>'”的等效功能,而无需先创建脚本。 - Soren
1个回答

10

如果您已安装了R,那么您也应该安装了程序Rscript,它可以用于运行R脚本:

Rscript myscript.r

您可以将以下代码放入bash脚本中:

#!/bin/bash

Rscript myscript1.r
Rscript myscript2.r
# other bash commands

这通常是在bash脚本中运行R脚本的最简单方式。

如果您想将脚本设置为可执行文件,以便通过键入./myscript.r来运行它,则需要找出您的Rscript安装位置,方法是键入:

which Rscript
# /usr/bin/Rscript

那么您的myscript.r将看起来像这样。
#!/usr/bin/Rscript

cross_correlation <- read.table(file.choose(), header=F, sep="\t")

barplot(cross_correlation$V3)
dev.copy(png,"cc.png",width=8,height=6,units="in",res=100)
dev.off()

hist(cross_correlation$V3, breaks=15, prob=T)

dev.copy(png,"hist_cc.png",width=8,height=6,units="in",res=100)
dev.off()

这种方法在这个问题中有所解释,可能会给您一些启示。


3
你也可以使用[#!/usr/bin/env Rscript]作为Shebang行。(Shebang行通常是指在Unix和Linux系统中,用于指定脚本解释器的第一行命令。) - Nick Kennedy
获取到错误信息:/runr.sh 错误:在“ cross_correlation <- read.table(file.choose(), header=F, sep="\t") cross_correlation.csv”中出现了意外符号 执行已停止 ./runr.sh: 第12行附近有语法错误 ./runr.sh: 第12行:` cross_correlation <- read.table(file.choose(), header=F, sep="\t")' - user2209882
在 dwcoder 上出现错误 - 我的 'myscript.r' 文件如下: #!/usr/bin/Rscript cross_correlation <- read.table(file.choose(), header=F, sep="\t") cross_correlation.csv barplot(cross_correlation$V3) dev.copy(png,"cc.png",width=8,height=6,units="in",res=100) dev.off()hist(cross_correlation$V3, breaks=15, prob=T)dev.copy(png,"hist_cc.png",width=8,height=6,units="in",res=100) dev.off() - user2209882

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