Home > Net >  How to change the level (hierarchy) of a nested list in r
How to change the level (hierarchy) of a nested list in r

Time:11-21

I have a nested list (see image) and I'd like to change the position of elements that are in the second level to first level and the name of this elements also changes. For example, element [enter image description here

CodePudding user response:

You can make a loop to create the new names, pasting the index of the first level element, ".", and 1 to the number of second level elements. I used purrr to do that, but you can choose any looping method you like.

The purrr::imap function iteratively takes each element from my_list and it's name (when it doesn't have a name, it's index), and passes it to the .x and .y arguments of the function written in the second argument.

Then, we flatten the list with unlist(my_list, recursive = FALSE), as @FactOREO suggested, and give it the new names.

names = purrr::imap(my_list, ~ paste0(.y, ".", 1:length(.x))) |> unlist()
my_list_new = unlist(my_list, recursive = FALSE) |> setNames(names)

Result:

# Dummy data
my_list = list(
  list(
    list("item 1.1"),
    list("item 1.2"),
    list("item 1.3")),
  list(
    list("item 2.1"),
    list("item 2.2"),
    list("item 2.3")))

> my_list_new
$`1.1`
$`1.1`[[1]]
[1] "item 1.1"


$`1.2`
$`1.2`[[1]]
[1] "item 1.2"


$`1.3`
$`1.3`[[1]]
[1] "item 1.3"


$`2.1`
$`2.1`[[1]]
[1] "item 2.1"


$`2.2`
$`2.2`[[1]]
[1] "item 2.2"


$`2.3`
$`2.3`[[1]]
[1] "item 2.3"

CodePudding user response:

I think this is a duplicate from here. You can use unlist(my_list, recursive = FALSE) to get a list of all regression model as first level entries.

  • Related