7

I have the commands below that I use to make plots in R. The main text file is cross_correlation.csv.

How can I put it in bash script so that when I launch it on the terminal, the R commands will perform their jobs and finish (like all other shell scripts).

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
  • 2
    possible duplicate of Run R script from command line Commented Jul 3, 2015 at 8:03
  • I was about to suggest R CMD BATCH script.r, so in my opinion it's a dupe. Commented Jul 3, 2015 at 8:05
  • Something like an equivalent to python -c '<commands>' would be nice without having to create a script first. Commented Sep 3, 2021 at 16:59

1 Answer 1

11

If you have R installed, you should also have the program Rscript installed, which can be used to run R scripts:

Rscript myscript.r

So you can put this line in a bash script:

#!/bin/bash

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

This is usually the easiest way to run R scripts inside bash scripts.

If you want to make the script executable so you can run it by typing ./myscript.r, you need to find out where your Rscript is installed by typing:

which Rscript
# /usr/bin/Rscript

Then your myscript.r will look like this

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

This method is explained in this question, which might also give you some ideas.

Sign up to request clarification or add additional context in comments.

3 Comments

Getting this error./runr.sh Error: unexpected symbol in " cross_correlation <- read.table(file.choose(), header=F, sep="\t") cross_correlation.csv" Execution halted ./runr.sh: line 12: syntax error near unexpected token (' ./runr.sh: line 12: cross_correlation <- read.table(file.choose(), header=F, sep="\t")'
Getting wrong @ dwcoder - My 'myscript.r' is #!/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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.