Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert complex list of lists to list of data frames

Tags:

list

split

r

I have a complex list that consists of other lists and data frames. I need to simplify this list to consist only from data frames - so each second level list should be made into separate first level data frames.

Here is reproducible example:

 dd<-data.frame(x=1:3,y=4:6)
 l1<-list(dd,list(dd,dd))
 #original list
 l1
[[1]]
  x y
1 1 4
2 2 5
3 3 6

[[2]]
[[2]][[1]]
  x y
1 1 4
2 2 5
3 3 6

[[2]][[2]]
  x y
1 1 4
2 2 5
3 3 6

Result I need to get

 l2<-list(dd,dd,dd)
 l2
[[1]]
  x y
1 1 4
2 2 5
3 3 6

[[2]]
  x y
1 1 4
2 2 5
3 3 6

[[3]]
  x y
1 1 4
2 2 5
3 3 6

I tried with the function unlist() and argument recursive=FALSE but in this case first level data frame is converted to two vectors.

 unlist(l1,recursive=FALSE)
$x
[1] 1 2 3

$y
[1] 4 5 6

[[3]]
  x y
1 1 4
2 2 5
3 3 6

[[4]]
  x y
1 1 4
2 2 5
3 3 6
like image 225
Didzis Elferts Avatar asked Jul 26 '13 07:07

Didzis Elferts


People also ask

Can you have a list of data frames?

To create a list of Dataframes we use the list() function in R and then pass each of the data frame you have created as arguments to the function.

How do I convert a list to a DataFrame in R?

Convert List to DataFrame using data. data. frame() is used to create a DataFrame in R that takes a list, vector, array, etc as arguments, Hence, we can pass a created list to the data. frame() function to convert list to DataFrame. It will store the elements in a single row in the DataFrame.

How do I make a list inside a list in Python?

Using append() function to create a list of lists in Python. What append() function does is that it combines all the lists as elements into one list. It adds a list at the end of the list.


1 Answers

One way I could think of is to check if the class of input (while running lapply) is data.frame or list, and if it's a data.frame convert it to a list of data.frame. This'll result the entire list becoming list of list of data.frames. Then you can use unlist with recursive=FALSE as follows:

unlist(lapply(l1, function(x) 
      if (class(x) == "data.frame") list(x) else x), recursive=FALSE)
[[1]]
  x y
1 1 4
2 2 5
3 3 6

[[2]]
  x y
1 1 4
2 2 5
3 3 6

[[3]]
  x y
1 1 4
2 2 5
3 3 6

This works of course when the data is as you mention exactly. They are either list of data.frames or list of list of data.frames. Oh and welcome to SO (first question)! :)

like image 58
Arun Avatar answered Dec 04 '22 09:12

Arun