# In Seurat, how can I export cluster IDs to csv files

I am doing scRNAseq analysis with Seurat.

I clustered the cells using the FindClusters() function.

What I want to do is to export information about which cells belong to which clusters to a CSV file.

In a Seurat object, we can show the cluster IDs by using Idents(・), but I have no idea how to export this to CSV files.

I would be grateful if you could show this by using the PMBC data (https://satijalab.org/seurat/articles/pbmc3k_tutorial.html) as an example.

I've recently done this with my own Seurat data; here's the process:

# load tidyverse packages
library(tidyverse)
# create cluster ID table
tibble(cellID = colnames(pbmc), clusterID = Idents(pbmc)) %>%
# write out to a file, with today's date
write_csv(file = sprintf("cluster_mappings_%s.csv", Sys.Date()))

• Thank you very much !! Oct 28 '21 at 6:08

The clusters information, together with additional information on each cells (%mito, sample name, group, orig.ident,...) are stored inside seuratObject@meta.data. write.csv(seuratObject@meta.data,"./seurat_metadata.csv") will dump everything to a file.

The method @osmoc suggested, is using built in seurat functions to interact with seuratObject@meta.data. seuratObject$graph_name_resolution points to seuratObject@meta.data$graph_name_resolution.

I personally prefer to use the metadata table, as I have more control on how I interact with the data.

• Thank you very much ! Oct 28 '21 at 6:09
• Using the meta.data slot is the best answer. The behavior of various shortcut methods can change between different versions of Seurat and even based on how you interact with your Seurat object. More generally, it is a bad idea to take columns from different sources when constructing a data frame. Oct 28 '21 at 14:19

The clusters are saved in the field object$seurat_clusters where object represents your Seurat object. You can also get them running the command Idents(object). NOTE: if you run the command FindClusters on different SNN graphs, or different resolutions, you need to specify the clusters by object$graph_name_resolution. Every time you run FindClusters, the idents of the cells are updated to the latest results, same for seurat_clusters.

For instance, let's say that you have run the command FindNeighbors on the RNA assay (default value).
Then you run FindClusters with graph = "RNA_snn" and resolution=1.
In that case, the clusters are in object\$RNA_snn_1.

Once you have the clusters, you can save them as a CSV:

clusters <-  <here you use one of the described methods>
# data.frame
clust.df <- data.frame(cellID = colnames(object), clusters = clusters)
write.csv(clust.df, <path.of.the.csv.file>)

• Thank you very much ! Oct 28 '21 at 2:53