This is a test version of Biostars. For the public version, visit https://www.biostars.org.
samtools and Rsamtools in r

Hello,

How can I use Rsamtools, so I can import the results from a bam file? E.g. if I use samtools view sample.bam > sample.sam, I can import this sam file easily into R. However, if I run Rsamtools, and do something like

input_bam <- "sample.bam"
output_sam <- "sample"
sam <- asSam(input_bam, destination = output_sam)

sample <- read.delim(output_sam, header=FALSE)

The imported data looks quite different, the latter one has a log of unaligned entries.

samtools

what do you mean by a "log of unaligned entries"?

The top sam file has been created with samtools view, and I can easily import it into R. The second has been done with asSAM, it does not properly load into R.

1 answer

one of your files has a SAM header (the @SQ tags etc); the other does not

the file that you generate with

samtools view sample.bam > sample.sam

is not actually a valid SAM file; it is missing the header because in the usecase the output is typically used to view the alignments at command line, in that usecase the headers get in the way,

to make it equivalent, and to produce a valid SAM file you would need to add the -h flag

samtools view -h sample.bam > sample.sam

Thank you Istvan Albert , I want the inverse to though, I want rsamtools to generate a Sam file without the headers and then load it into at for further manipulation. So I want the Sam file generated by samtools view.

Rsamtools likely won't generate that output, since that is a subset of a proper SAM output.

You could post-process that file to remove the headers with another line of code or ignore the lines that start with @ when reading the file.

perhaps you could set

read.delim(..., comment.char ='@')

Log in to answer this question.