Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list to a data frame

Tags:

list

dataframe

r

I have a nested list of data. Its length is 132 and each item is a list of length 20. Is there a quick way to convert this structure into a data frame that has 132 rows and 20 columns of data?

Here is some sample data to work with:

l <- replicate(   132,   as.list(sample(letters, 20)),   simplify = FALSE ) 
like image 853
Btibert3 Avatar asked Nov 19 '10 16:11

Btibert3


People also ask

Can we create DataFrame from list?

The pandas DataFrame can be created by using the list of lists, to do this we need to pass a python list of lists as a parameter to the pandas. DataFrame() function. Pandas DataFrame will represent the data in a tabular format, like rows and columns.

How do I convert a list to pandas?

Convert data to list. Since there is no method to convert pandas. DataFrame , pandas. Series directly to list , first get the NumPy array ndarray with the values attribute, and then use tolist() method to convert to list .

Is a list a DataFrame?

Data frames are lists as well, but they have a few restrictions: you can't use the same name for two different variables. all elements of a data frame are vectors. all elements of a data frame have an equal length.


2 Answers

With rbind

do.call(rbind.data.frame, your_list) 

Edit: Previous version return data.frame of list's instead of vectors (as @IanSudbery pointed out in comments).

like image 144
Marek Avatar answered Sep 19 '22 21:09

Marek


Update July 2020:

The default for the parameter stringsAsFactors is now default.stringsAsFactors() which in turn yields FALSE as its default.


Assuming your list of lists is called l:

df <- data.frame(matrix(unlist(l), nrow=length(l), byrow=TRUE)) 

The above will convert all character columns to factors, to avoid this you can add a parameter to the data.frame() call:

df <- data.frame(matrix(unlist(l), nrow=132, byrow=TRUE),stringsAsFactors=FALSE) 
like image 43
nico Avatar answered Sep 20 '22 21:09

nico