From f89d61e1b10e7fdcd41808ca851de9720afbd930 Mon Sep 17 00:00:00 2001 From: Jack Leary Date: Sun, 7 Apr 2024 14:26:59 -0400 Subject: [PATCH] finally fixed sorting fn --- R/sortObservations.R | 19 +++++++++++++------ man/sortObservations.Rd | 1 + 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/R/sortObservations.R b/R/sortObservations.R index 0103f76..bdc517c 100644 --- a/R/sortObservations.R +++ b/R/sortObservations.R @@ -11,6 +11,7 @@ #' @details #' \itemize{ #' \item If the input is a matrix, it is assumed that the columns are cells - and are named as such - and the rows are genes. +#' \item If the input is a Seurat object, sorting requires converting to \code{SingleCellExperiment} object first, then ordering, then converting back toa \code{Seurat} object. Some information might be lost, so it is recommended not to overwrite your original \code{Seurat} object. #' } #' @export #' @examples @@ -27,17 +28,23 @@ sortObservations <- function(expr.mat = NULL, if (is.null(expr.mat) || is.null(pt) || is.null(id.vec)) { stop("You forgot some inputs to sortObservations().") } if (any(is.na(id.vec))) { stop("The subject ID vector must not contain any NA values.") } # create table with subject ID and pseudotime - subj_df <- data.frame(ID = id.vec, - PT = pt.vec, - Cell = colnames(expr.mat)) + subj_df <- data.frame(Cell = colnames(expr.mat), + ID = id.vec, + PT = pt.vec) # arrange by subject ID then pseudotime subj_df <- dplyr::arrange(subj_df, ID, PT) # sort object by cells - expr.mat <- expr.mat[, subj_df$Cell] - if (!is.unsorted(colnames(expr.mat))) { - stop("Sorting has failed.") + if (inherits(expr.mat, "SingleCellExperiment") || inherits(expr.mat, "matrix") || inherits(expr.mat, "dgCMatrix")) { + expr.mat <- expr.mat[, subj_df$Cell] + } else if (inherits(expr.mat, "Seurat")) { + warning("Ordering a Seurat object requires conversion to SingleCellExperiment, and some information might be lost.") + sce <- Seurat::as.SingleCellExperiment(expr.mat) + sce <- sce[, subj_df$Cell] + expr.mat <- Seurat::as.Seurat(sce) + } else { + stop("Unrecognized input class.") } return(expr.mat) } diff --git a/man/sortObservations.Rd b/man/sortObservations.Rd index 8915e45..ce16fca 100644 --- a/man/sortObservations.Rd +++ b/man/sortObservations.Rd @@ -22,6 +22,7 @@ Since the GEE & GLMM modes require data to be sorted by sample ID and pseudotime \details{ \itemize{ \item If the input is a matrix, it is assumed that the columns are cells - and are named as such - and the rows are genes. +\item If the input is a Seurat object, sorting requires converting to \code{SingleCellExperiment} object first, then ordering, then converting back toa \code{Seurat} object. Some information might be lost, so it is recommended not to overwrite your original \code{Seurat} object. } } \examples{