rlistdata-structures

How to flatten two nested lists into one list in R?


I have a list which nests a list like this:

 >>>View(mylist)
[

[{"id":1, "name": "Jack"},{"id":2, "name": "Mike"}],

[{"id":3, "name": "Mary"},{"id":4, "name": "Bob"}],

]

Now, I want to remove this inner layer of list, so it should be:

 >>>View(mylist)
[

{"id":1, "name": "Jack"},{"id":2, "name": "Mike"},

{"id":3, "name": "Mary"},{"id":4, "name": "Bob"},

]

In python, it's easy to achieve, just using compression list:

[subitem for item in mylist for subitem in item]

or using itertools:

import itertools
list(itertools.chain.from_iterable(mylist))

However, in R language, I feel a little tricky. I try to using do.call:

do.call(c, mylist)

It works well. However, when my nest list is large like this:

enter image description here

enter image description here

After using do.call(),I got the result like this:

enter image description here

The output format is not like the previous, so what's the problem?

By the way, you can construct the above mentioned "mylist" using the following R code:

mylist <- list(
  list(
    list(id = 1, name = "Jack"),
    list(id = 2, name = "Mike")
  ),
  list(
    list(id = 3, name = "Mary"),
    list(id = 4, name = "Bob")
  )
)

And "data1":

data1 <- list(
  data.frame(
    id = c(3, 4),
    name = c("John", "Anna")
  ),
  data.frame(
    id = c(5, 6),
    name = c("Tom", "Jerry")
  )
)

Solution

  • Here is one option using base R -

    We unlist mylist by one-level and turn the individual elements in dataframe and rbind them together. Since data1 is already a list of dataframes we can rbind them directly.

    Finally we combine the two datasets together to get final output.

    # Thanks to @Friede for the comment. 
    data_1 <- do.call(rbind.data.frame, unlist(mylist, recursive = FALSE))
    data_2 <- do.call(rbind, data1)
    
    rbind(data_1, data_2)
    
    #  id  name
    #1  1  Jack
    #2  2  Mike
    #3  3  Mary
    #4  4   Bob
    #5  3  John
    #6  4  Anna
    #7  5   Tom
    #8  6 Jerry
    

    Note that the temporary variables data_1 and data_2 are created just for clarity purposes and are not required.