Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a bash script from an R script

Tags:

bash

r

So I have this programme samtools that I want to use from cmd line, converting one file to another. It works like this:

bash-4.2$ samtools view filename.bam | awk '{OFS="\t"; print ">"$1"\n"$10}' - > filename.fasta

As I want to automate this, I would like to automate it by using an R script. I know you can use system() to run an OS command, but I cannot get it to work by trying

system(samtools view filename.bam | awk '{OFS="\t"; print ">"$1"\n"$10}' - > filename.fasta)

Is it just a matter of using regexes to get rid of spaces and stuff so the comma nd argument system(command) is readable? How do I do this?

EDIT:

system("samtools view filename.bam | awk '{OFS="\t"; print ">"$1"\n"$10}' - > first_batch_1.fasta") Error: unexpected input in "system("samtools view filename.bam | awk '{OFS="\"

EDIT2:

system("samtools view filename.bam | awk '{OFS=\"\t\"; print \">\"$1\"\n\"$10}' - > filename.fasta")

awk: cmd. line:1: {OFS="    "; print ">"$1"
awk: cmd. line:1:                         ^ unterminated string
awk: cmd. line:1: {OFS="    "; print ">"$1"
awk: cmd. line:1:                         ^ syntax error
> 

EDIT3: And the winner is:

system("samtools view filename.bam | awk '{OFS=\"\\t\"; print \">\"$1\"\\n\"$10}' -> filename.fasta")
like image 760
cianius Avatar asked Jul 09 '12 12:07

cianius


People also ask

How do I run a terminal command in R?

RStudio supports multiple terminal sessions. To start another terminal session, use the New Terminal command on the Terminal dropdown menu, or Alt+Shift+R.

How do I run a Linux command in RStudio?

In RStudio, commands can be executed from shell scripts by pressing Ctrl + Enter .

How do I run an entire script in R?

To run the entire document press the Ctrl+Shift+Enter key (or use the Source toolbar button).


1 Answers

The way to debug this is to use cat to test whether your character string has been escaped correctly. So:

  1. Create an object x with your string
  2. Carefully escape all the special characters, in this case quotes and backslashes
  3. Use cat(x) to inspect the resulting string.

For example:

x <- 'samtools view filename.bam | awk \'{OFS="\\t"; print ">"$1"\\n"$10}\' - > filename.fasta'

cat(x)
samtools view filename.bam | awk '{OFS="\t"; print ">"$1"\n"$10}' - > filename.fasta

If this gives the correct string, then you should be able to use

system(x)
like image 199
Andrie Avatar answered Sep 20 '22 05:09

Andrie