-
-
Save adomingues/95c78846f964e985ab21886dca543a38 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