Home > Blockchain >  How to create a new list for each iteration of for loop in R?
How to create a new list for each iteration of for loop in R?

Time:08-14

I want to create a new list each time a for loop runs. And I want to name them based on a character vector. Currently this is how the code goes:

for (c in my_vector){
    x <- DBI:dbGetQuery(conn=con, statement=query)
    filename <- x[ ,c(3)]
    my_list <- list()
    for (i in 1:length(filename)){
         y <- DBI:dbGetQuery(conn=con, statement=query2)
         name <- filename[i]
         tmp <- list(y)
         my_list[[name]] <- tmp
     }
}

I want to create a separate/new list for each element of my_vector and then fill the list elements with another for loop. However, current code overwrites this list and it only saves data from last iteration of for loop. Any suggestions on how I can achieve this?

CodePudding user response:

This code will produce lists equal to the length of my_vector having names my_list_v1 , my_list_v2 and so on, where v1 ,v2 , .... are the elements of my_vector

for (c in my_vector){
    x <- DBI:dbGetQuery(conn=con, statement=query)
    filename <- x[ ,c(3)]
    my_list <- paste0("my_list" ,"_", c)
    l <- list()
    for (i in 1:length(filename)){
         y <- DBI:dbGetQuery(conn=con, statement=query2)
         name <- filename[i]
         tmp <- list(y)
         l[[name]] <- tmp
     }
     assign( my_list , value = l)
}
  • Related