使用 bash 脚本运行 R 命令

use*_*882 4 command r

我有下面的命令用于在 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()
Run Code Online (Sandbox Code Playgroud)

dwc*_*der 7

如果您安装了 R,则还应该Rscript安装该程序,该程序可用于运行 R 脚本:

Rscript myscript.r
Run Code Online (Sandbox Code Playgroud)

因此,您可以将此行放在 bash 脚本中:

#!/bin/bash

Rscript myscript1.r
Rscript myscript2.r
# other bash commands
Run Code Online (Sandbox Code Playgroud)

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

如果您想让脚本可执行以便您可以通过键入 来运行它./myscript.r,您需要通过键入以下内容来找出您Rscript的安装位置:

which Rscript
# /usr/bin/Rscript
Run Code Online (Sandbox Code Playgroud)

那么你的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()
Run Code Online (Sandbox Code Playgroud)

这个方法在这个问题中有解释,也可能会给你一些想法。

  • 您还可以使用 [`#!/usr/bin/env Rscript` 作为shebang 行](http://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-在 Python 脚本的第一行)。 (2认同)