1

I am trying to obtain the number of cells that are expressing the genes of interest(the gene names are stored in the data frame 'fibmatch') or control (Osr1) in each cluster using a for loop. I want to create a data frame with the frequency of each gene in each cluster. However, the for loop I have created is only saving the last iteration. Could someone give me suggestions on how to fix this? Thanks!

df = data.frame()
for (i in 1:nrow(fibmatch)){
  obj <- subset(x = adult, subset = fibmatch[i,1] > 0 | Osr1 > 0)
  obj <- obj@meta.data[["seurat_clusters"]]
  obj <- table(obj)
  df <- rbind(df,obj)
}

By creating an empty data frame and using rbind, I was attempting to save each iteration but it only saved the last iteration.

  • 3
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Are you checking the value of `df` or `obj` at the end? Also its usually better not to bind in loop. It's better to generate all values in a list with something like `lapply/Map` and then bind at the end. It results in fewer memory reallocations and is a lot faster in most cases. – MrFlick Oct 28 '22 at 18:04
  • You have two sides in your loop, the left hand side (LHS) and right hand side (RHS), and right now your are doing LHS <- RHS[i], so, somewhat naturally, LHS will always, and only return the last RHS[i]. IF, LHS is a, say obj <- list(), established outside the loop, then obj[[i]] <- RHS[i], might serve you. Whether it is LHS `[[` <- RHS '[', or LHS`[` <- RHS`[[`, depends on which are lists `[[` or vectors `[`. You'd know better as you have the data. Decide, and define `obj` as list or vector outside the `for` loop. – Chris Oct 29 '22 at 02:45

0 Answers0