Created
August 26, 2022 17:02
-
-
Save mfansler/5cfcaad391b2e7862af54a260e1972a2 to your computer and use it in GitHub Desktop.
Read anndata dataframes with pure R
This file contains hidden or 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
| library(rhdf5) | |
| library(tidyverse) | |
| read_ad_df <- function (file, name) { | |
| x_attrs <- h5readAttributes(file, name) | |
| ## check requested entry is a dataframe | |
| ## TODO: do we need to check encoding-version? | |
| stopifnot(x_attrs[['encoding-type']] == "dataframe") | |
| ## rownames and columns in order | |
| idx_cols <- unlist(x_attrs[c("_index", "column-order")], use.names=FALSE) | |
| ## load the factor levels | |
| x_levels <- h5read(file, str_c(name, "/__categories")) | |
| ## load dataframe | |
| h5read(file, name)[idx_cols] %>% as_tibble() %>% | |
| ## replace categorical columns with proper factors | |
| mutate(across(any_of(names(x_levels)), ~ factor(x_levels[[cur_column()]][.x+1L]))) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This can be used on
h5adfiles fromanndatato load what were originially PandasDataFrameobjects. For example, for single-cell data the equivalent ofcolData()on aSingleCellExperimentobject would be found in/obsin the HDF5 object:and
rowDatais found at/varNote on Motivation
There is an
anndataR package, so why not use that? Becauseanndatais a wrapper for calling the Pythonanndatapackage, rather than a pure R package. For a well-defined specification, it seems unnecessary to load an entire Python subprocess for what can be done directly in R.