Last active
January 3, 2019 09:13
-
-
Save SamBuckberry/9914246 to your computer and use it in GitHub Desktop.
Import a bam file into R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# install the Rsamtools package if necessary | |
source("http://bioconductor.org/biocLite.R") | |
biocLite("Rsamtools") | |
# load the library | |
library(Rsamtools) | |
# specify the bam file you want to import | |
bamFile <- "test.bam" | |
# A function to read bam file | |
readBAM <- function(bamFile){ | |
bam <- scanBam(bamFile) | |
# A function for collapsing the list of lists into a single list | |
# as per the Rsamtools vignette | |
.unlist <- function (x){ | |
x1 <- x[[1L]] | |
if (is.factor(x1)){ | |
structure(unlist(x), class = "factor", levels = levels(x1)) | |
} else { | |
do.call(c, x) | |
} | |
} | |
bam_field <- names(bam[[1]]) | |
list <- lapply(bam_field, function(y) .unlist(lapply(bam, "[[", y))) | |
bam_df <- do.call("DataFrame", list) | |
names(bam_df) <- bam_field | |
#return a list that can be called as a data frame | |
return(bam_df) | |
} | |
# Load the bam file | |
bam1 <- readBAM(bamFile) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Sam,
I am trying to read a BAM file and it takes a long time and it fails.
Do you have any recommendation?
Best,