scverse/anndataR

Add `example_anndata` constructor

Closed this issue · 3 comments

To avoid having to copy and paste this every time:

#' @examples
#' ad <- InMemoryAnnData$new(
#'   X = matrix(1:5, 3L, 5L),
#'   obs = data.frame(cell = 1:3),
#'   obs_names = letters[1:3],
#'   var = data.frame(gene = 1:5),
#'   var_names = letters[1:5]
#' )

We can define a new function to provide a small, configurable anndata object:

example_anndata <- function(n_obs=3L,
                            n_vars=5L){
  InMemoryAnnData$new(
    X = matrix(seq(n_vars), n_obs, n_vars),
    obs = data.frame(cell = seq(n_obs)),
    obs_names = letters[seq(n_obs)],
    var = data.frame(gene = seq(n_vars)),
    var_names = letters[seq(n_vars)]
  )
}

So now the example looks like:

#' @examples
#' ad <- example_anndata()

This will also be helpful if we want to change the default example at any point, since we'll only need to change the code in one spot.

I generalized this even further to include Seurat objects, for quick access to examples:

#' Example AnnData
#' 
#' Create a small example AnnData object.
#' @param n_obs Number of observations.
#' @param n_var Number of variables.
#' @param output_class Name of the AnnData class. 
#' Must be one of:
#' \itemize{
#' \item{"InMemoryAnnData": }{Produces \link[anndataR]{InMemoryAnnData}}
#' \item{"HDF5AnnData": }{Produces \link[anndataR]{HDF5AnnData}}
#' \item{"Seurat": }{Produces \link[SeuratObject]{Seurat}}
#' }
#' @param ... Additional arguments passed to the generator function.
#' See the "Details" section for more information on which parameters.
#' @returns \link[anndataR]{InMemoryAnnData} or 
#' \link[anndataR]{HDF5AnnData} or link[SeuratObject]{Seurat}.
#' @export
#' @examples
#' example_anndata()
example_data <- function(n_obs=3L,
                         n_var=5L,
                         output_class=c("InMemoryAnnData",
                                           "HDF5AnnData",
                                           "Seurat"),
                         ...){
  
  output_class <- output_class[1]
  generator <- get_generator(
    if(output_class=="Seurat") "InMemoryAnnData" else output_class
  )
  ad <- generator$new(
    X = matrix(seq(n_var), n_obs, n_var),
    obs = data.frame(cell = seq(n_obs)),
    obs_names = letters[seq(n_obs)],
    var = data.frame(gene = seq(n_var)),
    var_names = letters[seq(n_var)],
    ...
  )
  if(output_class=="Seurat"){
    return(to_Seurat(ad))
  } else {
    return(ad)
  }
}

Ah, actually I missed the function: dummy_data. It makes more sense to integrate my extensions to this.