0

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 [1][1] turns into [[1.1]], element [1][[2]] turns into [[1.2]], element [1][[3]] turns into [[1.3]] and so on. It needs to be happen in all elements.

It's a huge list where a put some regressions results and I want to compare them using compare_performance from Performance package.

Does anyone know how to do it in fast and easily way ?

I tried unlist but it becomes a mess. I tried flatten from rlist but I get the same result unlist.

enter image description here

2 Answers2

1

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.

FactOREO
  • 86
  • 4
1

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"