Ivo
Ivo

Reputation: 4200

use append() and get() to form list of lists

I have a list of list names and corresponding lists like this:

list_names <- list("name1", "name2", "name3")
name1 <- list("apple", "banana", "orange", "peach")
name2 <- list("foo", "bar", "baz")
name3 <- list("house", "tree")

I now want to create a list of lists, with each list entry containing one of the lists name1 - name3.

I tried the following code unsuccessfully but am stuck:

list_of_lists <- list()
for (i in 1:length(list_names)){
    ls <- list_names[[i]]
    append(list_of_lists, get(ls))
    }

The code runs without errors but list_of_lists us a List of 0, while I expect it to look like this:

> list_of_lists
$name1
$name1[[1]]
[1] "apple"
$name1[[2]]
[1] "banana"
$name1[[3]]
[1] "orange"
$name1[[4]]
[1] "peach"
$name2
$name2[[1]]
[1] "foo"
$name2[[2]]
[1] "bar"
$name2[[3]]
[1] "baz"
$name3
$name3[[1]]
[1] "house"
$name3[[2]]
[1] "tree"

What am I missing?

Upvotes: 1

Views: 44

Answers (2)

sempervent
sempervent

Reputation: 893

Instead of iterating over the numerical list, iterate over each item:

list_of_lists <- list()
for (i in list_names){
   list_of_lists[[i]] <- get(i)
}

Upvotes: 2

Ben Bolker
Ben Bolker

Reputation: 226182

append doesn't work the same way as list.append in Python - it returns a new value rather than modifying the list in place. So you should use list_of_lists <- append(list_of_lists, get(ls)) in your loop.

You could also consider

list_of_lists <- lapply(list_names, get)

as a one-line (and maybe more R-idiomatic) solution.

Upvotes: 3

Related Questions