Question: Convert BAM to FASTQ
gravatar for ioannis.vardaxis
5 months ago by
ioannis.vardaxis30 wrote:


In my package I was using rbamtools from CRAN for converting some BAM files to FASTQ. However rbamtools is now depressed, so I was wondering if there is any function in Bioconductor which can do that. I tried to find it myself with no luck.


bam fastq • 176 views
ADD COMMENTlink modified 5 months ago by Martin Morgan ♦♦ 23k • written 5 months ago by ioannis.vardaxis30

Hi ioannis.vardaxis, I never done this in R environment but I can assure that is very easy using samtools in unix. this is the code:

samtools fastq input.bam > output.fastq

if your BAM is a paired end you have to split the fastq generated

cat output.fastq | grep '^@.*/1$' -A 3 --no-group-separator > sample_mate1.fastq 
cat output.fastq | grep '^@.*/2$' -A 3 --no-group-separator > sample_mate2.fastq
ADD REPLYlink modified 5 months ago • written 5 months ago by Merlin 10

Thanks, but I need it in R since it is part of my R-package :/

ADD REPLYlink written 5 months ago by ioannis.vardaxis30
Answer: Convert BAM to FASTQ
gravatar for Martin Morgan
5 months ago by
Martin Morgan ♦♦ 23k
United States
Martin Morgan ♦♦ 23k wrote:

Load Rsamtools and ShortRead


Create a BamFile that references your file, with a yieldSize (number of records available at one time). Open it

bf = BamFile("<path/to/bam">, yieldSize = 1000000)
to = "<path/to/fastq>"

Write a helper function to read and write one chunk

fun <- function(bf, to) {
    chunk <- scanBam(bf, param = ScanBamParam(what = c("seq", "qual")))
    fq <- ShortReadQ(chunk[[1]]$seq, chunk[[1]]$qual)
    writeFastq(fq, to, "a")

and apply this to each chunk

repeat {
    ## maybe indicate progress?
    len <- fun(bf, to)
    if (len == 0L)
ADD COMMENTlink written 5 months ago by Martin Morgan ♦♦ 23k

Thank you ! This did the job :)

ADD REPLYlink written 5 months ago by ioannis.vardaxis30
Please log in to add an answer.


Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 16.09
Traffic: 134 users visited in the last hour