Skip to content

Instantly share code, notes, and snippets.

@ATpoint
Created January 23, 2024 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ATpoint/6ba2f8f83eb95f8e67e4734c940432be to your computer and use it in GitHub Desktop.
Save ATpoint/6ba2f8f83eb95f8e67e4734c940432be to your computer and use it in GitHub Desktop.
Standalone function to read loom files from velocyto into R as CsparseMatrix, adapted from velocyto.R.
#' Read loom files into R as CsparseMatrix, depending on Matrix and hdf5r
#' @param path to file loom file on disk
#' @param include.ambiguous logical, whether to also read the "ambiguous" counts from velocyto, default FALSE
#'
readLoomMatrices <- function(file, include.ambiguous=FALSE) {
require(Matrix)
require(hdf5r)
engine='hdf5r'
if (engine == 'hdf5r') {
f <- hdf5r::H5File$new(file, mode='r')
cells <- f[["col_attrs/CellID"]][]
genes <- f[["row_attrs/Accession"]][]
dl <- c(spliced="layers/spliced",
unspliced="layers/unspliced",
ambiguous="layers/ambiguous")
if(!include.ambiguous) {
dl <- dl[c("spliced", "unspliced")]
}
if("layers/spanning" %in% hdf5r::list.datasets(f)) {
dl <- c(dl, c(spanning="layers/spanning"))
}
dlist <- lapply(dl, function(path) {
m <- as(t(f[[path]][,]),'CsparseMatrix')
rownames(m) <- genes; colnames(m) <- cells;
return(m)
})
f$close_all()
return(dlist)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment