Hi All,
I am working on Single-cell dataset, I wanted to extract raw counts of clusters (Say cluster num 4,6,8) and save it as a csv file. but I am not able to do the same, I have used the following codes,
alldata_epi <- subset(alldata, idents = c(1,23,5,18,22,15))
counts <- alldata_epi@assays$RNA@counts
but when I check the counts, it is not showing anything,
> counts
[,1]
[1,] NA
>
Please let me know where I am going wrong.
Thanks and regards,
Dave
1 answer
The output that you show for the print command on the counts object indicates a single NA value, which conflicts with the dimensions that you later report for the full object (22,294 rows by 780 columns). This suggests a possible error in how the object was inspected or assigned, or that the @counts slot contains unexpected NA values, which is not typical for raw count data in a Seurat object (raw counts should be non-negative integers, with zeros for no expression).
First, verify that your subset operation selects cells correctly. The identities that you use in subset() must match the levels in Idents(alldata). Run the following to check:
levels(Idents(alldata))
table(Idents(alldata))
If the specified identities (such as 1, 23, 5, 18, 22, 15) do not exist or contain no cells, then alldata_epi will have zero cells, leading to an empty or malformed counts matrix. In that case, adjust the identities to match your target clusters (for example, 4, 6, 8).
Next, inspect the structure of the counts matrix properly, as it is likely a sparse matrix (dgCMatrix class from the Matrix package). Printing the entire matrix may not display all contents if it is large; instead, examine a subset:
str(alldata@assays$RNA@counts)
alldata@assays$RNA@counts[1:10, 1:20]
alldata_epi@assays$RNA@counts[1:10, 1:20]
A normal sparse matrix will show dots (.) for zeros and numbers for counts. If NA values appear, replace them with zeros to correct the data:
counts[is.na(counts)] <- 0
To extract the raw counts without subsetting the entire object (which can be memory-intensive), select the cells directly:
target_cells <- colnames(alldata)[Idents(alldata) %in% c(4, 6, 8)]
counts <- alldata@assays$RNA@counts[, target_cells]
Finally, to save as a CSV file, convert the sparse matrix to dense format if necessary (note that this may consume memory for large datasets):
write.csv(as.matrix(counts), file = "raw_counts_clusters.csv", row.names = TRUE)
Kevin
Log in to answer this question.
Ok, I just checked that it should have worked. Did you check the subsetted object to see if there are some errors?
This will show you if number of cells are same in selected clusters after subsetting.
Then, when you get the counts object, check its dimension?
Could you post these outputs?
Thanks a lot for the reply, i just checked its shows the following
Ok, it seems you have NA in your original data also, so it is not coming from subsetting.
check your counts in the sparse matrix.
my sparse matrix looks like this