This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to get subset of a Seurat object based on metadata?

I have a Seurat object in which the meta.data include a column name "predicted_cell_type". The values of this column include "0:CD8 T cell", "1:CD4 T cell", "2:spinous cell", etc.

I would like to extract the "0:CD8 T cell" from the object and use the following command:

subset(skin, subset = skin@meta.data[['predicted_cell_type']] == '0:CD8 T cell')

but it gives the following error:

Error in FetchData.Seurat(object = object, vars = unique(x = expr.char[vars.use]),  : 
  None of the requested variables were found:

Do you know what is the correct command to do this?

With many thanks

scrna-seq seurat

2 answers

You do not need to include skin@meta.data[['predicted_cell_type']] in your subset function. Try the following instead:

subset(skin, subset = predicted_cell_type == '0:CD8 T cell')

As an example see https://satijalab.org/seurat/articles/essential_commands.html

This command gives:

Error: No cells found

Do you have cells labeled "0:CD8 T Cell" in skin$predicted_cell_type?

> skin$predicted_cell_type 
Error in rep.int(x = colnames(x = x), times = length(x = i)) :    unimplemented type 'NULL' in 'rep3'

but cells labeled as '0:CD8 T cell' do exit.

> unique(skin@meta.data[['predicted_cell_type']] == '0:CD8 T cell')
[1] FALSE  TRUE

Hmm, not sure why subset doesn't match to '0:CD8 T cell' but maybe it's the ":"?

An alternative option is the following:

idx <- which(skin$predicted_cell_type == '0:CD8 T cell')
skin <- skin[,idx]

To keep the subset call as clean as possible, you can:

Idents(skin) <- "predicted_cell_type" 
cell_values <- c("0:CD8 T cell")
subset(skin, idents = cell_values, invert = FALSE)
> Idents(skin) <- "predicted_cell_type" 
Warning message:
In `Idents<-.Seurat`(`*tmp*`, value = "predicted_cell_type") :
  Cannot find cells provided
> cell_values <- c("0:CD8 T cell")
> subset(skin, idents = cell_values, invert = FALSE)
Error in WhichCells.Seurat(object = x, cells = cells, idents = idents,  : 
  Cannot find the following identities in the object: 0:CD8 T cell

You should check the consistency of both your seurat object and the meta.data table. I tried to add some identities formatted like yours to one of my dataset and my code worked fine. See below

Log in to answer this question.