Annalise Azzopardi
Annalise Azzopardi

Reputation: 123

Convert Bam File to CSV

I have a bam file does anyone know how to convert a bam file to a csv file? I am trying to use R-software to open the bam file but I am not sure how to get the variables from the bam files so far I have used the below mentioned coding:

rm(list=ls())

#install bam packages
source("http://bioconductor.org/biocLite.R")
biocLite("Rsamtools",suppressUpdates=TRUE)
biocLite("RNAseqData.HNRNPC.bam.chr14",suppressUpdates=TRUE)
biocLite("GenomicAlignments",suppressUpdates=TRUE)


#load library
library(Rsamtools)
library(RNAseqData.HNRNPC.bam.chr14)
library(GenomicAlignments)
bamfile <- file.path("C:","Users","azzop","Desktop","I16-1144-01-esd_m1_CGCTCATT-AGGCGAAG_tophat2","accepted_hits.bam")
gal<-readGAlignments(bamfile)
gal
length(gal)
names(gal)

When I inserted names(gal) it gave me NULL not sure it is the correct.

I would like to convert the bam to csv and it would be easier to read the data

Upvotes: 2

Views: 2105

Answers (1)

pogibas
pogibas

Reputation: 28309

I would suggest converting BAM to BED and then reading BED file into R.

You can convert BAM to BED using bedtools.

This abstract code should work:

bamfile <- "C:/Users/azzop/Desktop/I16-1144-01-esd_m1_CGCTCATT-AGGCGAAG_tophat2/accepted_hits.bam"
# This code line sends command to convert BAM to BED (might take some time)
system(paste("bedtools bamtobed -i", bamfile, "> myBed.bed"))
library(data.table)
myData <- fread("myBed.bed")

Here I'm using function fread from a data.table package for a fast data read.

Upvotes: 2

Related Questions