Search code examples
rfor-loopnull

How can I compose two lists into one list (list of lists) by using for loop? The result has NULL value


I am trying the merge hundreds lists to one.Not intend to modify the contents of lists, I just want to sequentially combine the lists. The names of lists has some rules, so I want to use for-loop with get() and paste0() function. But The for-loop only showed me NULL value. Here is the simple example which reflect my case.

These are the lists what I want to merge.

list_a <- list(1, 2, 3, 4)
list_b <- list('a', 'b', 'c', 'd')

When I use list function directly, I can sucessfully get what I wanted

> list(list_a, list_b)
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 2

[[1]][[3]]
[1] 3

[[1]][[4]]
[1] 4


[[2]]
[[2]][[1]]
[1] "a"

[[2]][[2]]
[1] "b"

[[2]][[3]]
[1] "c"

[[2]][[4]]
[1] "d"

However, when I use for loop, I just could draw NULL value like below

naming <- c("list_a", "list_b")

aa <- list()
result <- for(i in 1:length(naming)){
aa[[i]] <- get(naming[i])  
}

> result
NULL

However, mysteriously, when I just dissolved the for-loop, I could get the right answer.

> list(get(naming[1]), get(naming[2]))
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 2

[[1]][[3]]
[1] 3

[[1]][[4]]
[1] 4


[[2]]
[[2]][[1]]
[1] "a"

[[2]][[2]]
[1] "b"

[[2]][[3]]
[1] "c"

[[2]][[4]]
[1] "d"

I don't know the reason why my for-loop not working. I attempted the designate the global enviorment in the function but it was not working too, only show NULL result.

Please give me some ideas to fix it.


Solution

  • I think that the problem is in your syntax, since you are setting the result variable equal to a loop. This code works for me:

    result <- list()
    for(i in 1:length(naming)) {
        result[[i]] <- get(naming[i])
    }
    
    result
    [[1]]
    [[1]][[1]]
    [1] 1
    
    [[1]][[2]]
    [1] 2
    
    [[1]][[3]]
    [1] 3
    
    [[1]][[4]]
    [1] 4
    
    
    [[2]]
    [[2]][[1]]
    [1] "a"
    
    [[2]][[2]]
    [1] "b"
    
    [[2]][[3]]
    [1] "c"
    
    [[2]][[4]]
    [1] "d"