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
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.
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.
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.
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)! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With