# The simplest way to convert a list with various length vectors to a data.frame in R

+1 vote
1 view

edited

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 as.data.frame(aa) 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.

Input:

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

Output:

A B

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.

ref:

## 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

0 votes
by (32.5k 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)

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer