Search code examples
rfor-loopseuratggsave

retreive Seurat object name in R during a for loop


I'm working on single cell rna-seq on Seurat and I'm trying to make a for() loop over Seurat objects to draw several heatmaps of average gene expression.

for(i in c(seuratobject1, seuratobject2, seuratobject3)){
  cluster.averages <- data.frame(AverageExpression(i, features = genelist))
  cluster.averages$rowmeans <- rowMeans(cluster.averages)
  genelist.new <- as.list(rownames(cluster.averages))
  cluster.averages <- cluster.averages[order(cluster.averages$rowmeans),]
  HMP.ordered <- DoHeatmap(i, features = genelist.new, size = 3, draw.lines = T)
  ggsave(HMP.ordered, file=paste0(i, ".HMP.ordered.png"), width=7, height=30)

the ggsave line does not work as it takes i as a seurat object. Hence my question: How to get ggsave() to use the name of my seurat object stored in "i"?

I tried substitute(i) and deparse(substitute(i)) w/o success.


Solution

  • Short answer: you can’t.

    Long answer: using substitute or similar to try to get i’s name will give you … i. (This is different for function arguments, where substitute(arg) gives you the call’s argument expression.)

    You need to use a named vector instead. Ideally you’d have your Seurat objects inside a list to begin with. But to create such a list on the fly, you can use get:

    names = c('seuratobject1', 'seuratobject2', 'seuratobject3')
    
    for(i in names) {
        cluster.averages <- data.frame(AverageExpression(get(i), features = genelist))
        # … rest is identical …
    }
    

    That said, I generally advocate strongly against the use of get and for treating the local environment as a data structure. Lists and vectors are designed to be used in this situation instead.