Nautica
Nautica

Reputation: 2018

Creating a sublist for elements within a list of lists after creation of list object

Sample list:

sublist <- list(foo = "foo", bar = "bar", baz = "baz")

sample_list <- list(a = sublist,
                    b = sublist,
                    c = sublist)

Here, I would like to create a sublist for the elements in a b and c within each of the aforementioned lists. I.e I would like to nest foo, bar, baz, one list further down, after I have created the list in the manner above.

Desired output:

sample_list <- list(a = list(a_down = sublist),
                    b = list(b_down = sublist),
                    c = list(c_down = sublist))

Upvotes: 2

Views: 91

Answers (1)

akrun
akrun

Reputation: 887118

We can use imap

library(purrr)
out2 <- imap(sample_list, ~ set_names(list(.x), paste0(.y, "_down"))) 

or making use of lst

imap(sample_list, ~ lst(!! paste0(.y, "_down") := .x))

-checking with OP's output

identical(out, out2)
#[1] TRUE

Upvotes: 1

Related Questions