Search code examples
rseurat

How to index R objects within a for loop?


I'm trying to use a for loop to simplify the following code:

a1 <- CreateSeuratObject (raw.data = a1.data)
a2 <- CreateSeuratObject (raw.data = a2.data)
a3 <- ...

I've tried the following:

samples <- c("a1", "a2", "a3")
samples.data <- c("a1.data", "a2.data", "a3.data")
for (i in samples) {
  for (j in samples.data) {
    i <- CreateSeuratObject(raw.data = j)    
  }
}

But it returns the following error:

Error in base::colSums(x, na.rm = na.rm, dims = dims, ...) : 
 'x' must be an array of at least two dimensions

The CreateSeuratObject function essentially tries to read the samples.data vector instead of indexing the corresponding item in the vector. How can I fix this?


Solution

  • Here are three ways of doing what you want. I suggest you do not use the first way.

    samples <- c("a1", "a2", "a3")
    samples.data <- c("a1.data", "a2.data", "a3.data")
    
    for (i in seq_along(samples)) {
        assign(samples[i], CreateSeuratObject(raw.data = samples.data[i]))
    }
    
    samples_list <- vector("list", length = length(samples))
    for (i in seq_along(samples)) {
      samples_list[[i]] <- CreateSeuratObject(raw.data = samples.data[i]))
    }
    names(samples_list) <- samples
    
    samples_list2 <- lapply(samples.data, CreateSeuratObject)
    names(samples_list2) <- samples