简体   繁体   中英

How to convert a list of nested lists of dataframes into a dataframe?

I have a list with nested lists of dataframes. The structure of my data is the following one:

在此处输入图片说明

How can I merge all the dataframes of the nested lists into an one dataframe? In this example I want a to merge (rbind) the 4 dataframes into one! For this example think that the initial list has length 3 instead of 58.

Thank you in advance!

First, loop inside 0, 18 and bind_rows then use map_dfr to bind rows of the higher element ie to bind 0 and 18 together.

library(purrr)
lst=list(`0`=list(`1`=iris[1:5,]),`18`=c(`1`=list(iris[1:5,]),`2`=list(iris[1:5,])))
map_dfr(ls,~bind_rows(.,.id='id'))
#OR
bind_rows(unlist(lst,recursive = FALSE),.id = 'id')

Another more save option is to use unlist and purrr::imap to produce column id represents the full path of each dataframe

imap_dfr(unlist(lst,recursive = FALSE), ~data.frame(id=.y, .x, stringsAsFactors = FALSE))

     id Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1   0.1          5.1         3.5          1.4         0.2  setosa
2   0.1          4.9         3.0          1.4         0.2  setosa
3   0.1          4.7         3.2          1.3         0.2  setosa
4   0.1          4.6         3.1          1.5         0.2  setosa
5   0.1          5.0         3.6          1.4         0.2  setosa
6  18.1          5.1         3.5          1.4         0.2  setosa
7  18.1          4.9         3.0          1.4         0.2  setosa
8  18.1          4.7         3.2          1.3         0.2  setosa
9  18.1          4.6         3.1          1.5         0.2  setosa
10 18.1          5.0         3.6          1.4         0.2  setosa
11 18.2          5.1         3.5          1.4         0.2  setosa
12 18.2          4.9         3.0          1.4         0.2  setosa
13 18.2          4.7         3.2          1.3         0.2  setosa
14 18.2          4.6         3.1          1.5         0.2  setosa
15 18.2          5.0         3.6          1.4         0.2  setosa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM