I'm trying to subset my seurat object based on colnames. I have gone ahead and labeled each cluster and now I want to subset all the colnames that are in Cancer_human for human_colnames and all the barcodes that are not in Cancer_human for mouse_colnames but get an error.

human_colnames = colnames(scData[,scData$cell_ann == "Cancer_human"])
mouse_colnames = colnames(scData[,!scData$cell_ann == "Cancer_human"])

Error in `[.Seurat`(scData, , scData$cell_ann == "Cancer_human") : Incorrect number of logical values provided to subset cells

I'm filtering on colnames not rownames. I want all the barcodes from the Cancer_human.

  • $\begingroup$ The code could only make sense if the data is a square, equal number of rows and columns. At the moment you are getting index from row comparison, then using that index to subset columns. Also, please provide a reproducible example data for testing, dput(myData). $\endgroup$
    – zx8754
    Aug 17, 2021 at 14:44
  • $\begingroup$ @zx8754 i agree for the reproducible example (consider the pbmc data set that comes with Seurat) but not the square argument (it would be correct for matrices) but Seurat objects contain multiple things and is implemented such that for a Seurat object so, so[, i] and so[[j]][i] both give information about cell i. $\endgroup$
    – jan-glx
    Jan 28 at 10:05

2 Answers 2


Did you tried the subset function?

# assuming that [email protected] looks like this
#         orig.ident  ...  cell_ann
# ATTCAA  sample1          Cancer_human
# ATTTAT  sample1          Cancer_human
# ...
# AAATCA  sampleX          Cancer_mouse
# ATTTAA  sampleX          Cancer_mouse

Idents(scData) <- "cell_ann"
human_subset <- subset(scData, idents = "Cancer_human")
mouse_subset <- subset(scData, idents = "Cancer_mouse") 
mouse_subset <- subset(scData, idents = "Cancer_human", invert = TRUE) # alternative way 

P.S. It is not clear what you are trying to do. You should add to your post how your data looks like.


If you want the column names to be preserved, you can subset the column names as a vector:

human_colnames = colnames(scData)[scData$cell_ann == "Cancer_human"]
mouse_colnames = colnames(scData)[!scData$cell_ann == "Cancer_human"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.