开发者

dynamically changing list name in loop using assign?

开发者 https://www.devze.com 2023-03-13 18:54 出处:网络
Best give an example: this code should, the way I see it, produce 10 lists with 100 elements each. for (i in 1:10){

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 ele开发者_如何转开发ments, but how can I fill element [[j]] in it? Thanks!


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.


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)


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
  }  
}
0

精彩评论

暂无评论...
验证码 换一张
取 消