maja
maja

Reputation: 11

dynamically changing list name in loop using assign?

Best give an example: this code should, the way I see it, produce 10 lists with 100 elements each.

for (i in 1:10){
assign(paste("List", i, sep="."), vector("list", length=100))
  for (j in 1:100){
    assign(paste("List", i, sep=".")[[j]], j+1)
  }
}

But it doesn't.. The first assign works fine, creates an empty list with 100 elements, but how can I fill element [[j]] in it? Thanks!

Upvotes: 1

Views: 6376

Answers (3)

wkmor1
wkmor1

Reputation: 7426

Problem is you can't use assign to assign values to elements of objects unless you get a bit tricky. See below.

for (i in 1:10){
  assign(paste("List", i, sep="."), vector("list", length=100))
  for (j in 1:100){
    assign(paste("List", i, sep="."), 
      {x <- get(paste("List", i, sep=".")) 
       x[[j]] <- j + 1 
       x})
  }
}

rm(i, j, x)

Upvotes: 6

Greg Snow
Greg Snow

Reputation: 49670

Instead of making 10 lists in the global environment, it would be much simpler to just make a list of lists:

mybiglist <- list()
for(i in 1:10) {
  mybiglist[[i]] <- list()
  for( j in 1:100 ) {
    mybiglist[[i]][[j]] <- j+1
  }
}

You can add names to any of the lists, or just access the parts by numeric subscripts. this also does not polute your global environment and is usually easier to debug. And when you want to do something with the 10 lists you can just use lapply/sapply instead of needing to fight another loop. You can also save/load/delete/explore/etc. one single object instead of 10.

Upvotes: 6

Grega Kešpret
Grega Kešpret

Reputation: 12117

Below code produces 10 lists with 100 elements each.

myList = list()

for (i in 1:10) {
      myList[[i]] = 1:100
}

However, not sure if you want 10 lists of vectors OR 10 lists of lists

In case you would like the latter, you can do something like:

myList = list()

for (i in 1:10) {
  myList[[i]] = list()

  for (j in 1:100) {
      myList[[i]][[j]] = j
  }  
}

Upvotes: 1

Related Questions