Explore Courses Blog Tutorials Interview Questions
+1 vote
in Data Science by (17.6k points)
edited by

Here I have a list with different length vectors. And I'd want to get a data.frame. I've seen lots of posts about it in SO (see ref), but none of them are as simple as I expected because this is really a common task in data preprocessing. Thank you.

Here simplest means if it works. So one function from the base package of R will be great. sapply(aa, "length<-", max(lengths(aa))) has four functions actually.

An example is shown below.


aa <- list(A=c(1, 3, 4), B=c(3,5,7,7,8))



1 3

3 5

4 7

NA 7

NA 8

A and B are the colnames of the data.frame.

One answer is sapply(aa, '[', seq(max(sapply(aa, length)))), but it's also complex.


  1. How to convert a list consisting of vector of different lengths to a usable data frame in R?

  2. Combining (cbind) vectors of different length

2 Answers

+1 vote
by (41.4k points)

You can use

data.frame(lapply(aa, "length<-", max(lengths(aa)))).

If you want to learn about R Programming visit this R Programming Online Training.

0 votes
by (32.3k points)

Let us take a scenario where your list of lists is called l. Then do:

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

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=length(l), byrow=T),stringsAsFactors=FALSE)

Related questions

0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer
asked May 23, 2019 in R Programming by Nigam (4k points)

Browse Categories