Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list of lists with different lengths to data.frame in R

Tags:

list

dataframe

r

I have read many answers in SO about converting list of lists to df. But, I have noticed that they all have the length of lists (within the main big list) to be the same. I have a different case:

h1 <- list(USA = c(10,13,17,11), RUSSIA = NULL, BRAZIL = NULL,
  CHINA = c(11,11,10,8,12), TAIWAN = c(12,9,9,11,9,12,14), CHILE = NULL)

I want to convert the above list h1 to a data.frame. My expected output should be a data.frame that has 2 columns - country_name, list. Something like this:

country_name, list
USA    [10, 13, 17, 11]
RUSSIA NULL
BRAZIL NULL
CHINA  [11, 11, 10, 8, 12]
TAIWAN [12, 9, 9, 11, 9, 12, 14]
CHILE  NULL

I did the follwing, but, did not work:

do.call(rbind, h1)

It tries to keep the column numbers same across all the rows. I do not want that. I want to see how I can use ldply to such cases. Any suggestion is appreciated.

like image 743
user1717931 Avatar asked Oct 13 '12 18:10

user1717931


People also ask

How do I combine lists into data frames in R?

Combining data frames in lists is very easy. All you need is the bind_rows or bind_cols function from the dplyr package. There are base R functions rbind and cbind as well, but I feel they don't always perform as well, especially if the order of the columns is not the same in the data frames.

Can a list contain a DataFrame in R?

DataFrames are generic data objects of R which are used to store the tabular data. They are two-dimensional, heterogeneous data structures. A list in R, however, comprises of elements, vectors, data frames, variables, or lists that may belong to different data types.

Can you have lists of lists in R?

The list is one of the most versatile data types in R thanks to its ability to accommodate heterogenous elements. A single list can contain multiple elements, regardless of their types or whether these elements contain further nested data. So you can have a list of a list of a list of a list of a list …

How do I find the length of a dataset in R?

The length() function returns the length of a given data frame.


2 Answers

Here's one way:

R> as.data.frame(as.matrix(h1))
                            V1
USA             10, 13, 17, 11
RUSSIA                    NULL
BRAZIL                    NULL
CHINA        11, 11, 10, 8, 12
TAIWAN 12, 9, 9, 11, 9, 12, 14
CHILE                     NULL

R> as.data.frame(as.matrix(h1))['TAIWAN', ]
$TAIWAN
[1] 12  9  9 11  9 12 14
like image 198
GSee Avatar answered Oct 03 '22 01:10

GSee


You can convert a list to a matrix, where every element of the matrix will be a list.

d1 <- data.frame(country_name=names(h1), list=matrix(h1))

That said, I recommend against doing this because it does not fit the R paradigm. Most R functions assume a matrix contains elements from one atomic type.

like image 37
Joshua Ulrich Avatar answered Oct 03 '22 00:10

Joshua Ulrich