The simplest way to convert a list with various length vectors to a data.frame in R
We can use
data.frame(lapply(aa, "length<-", max(lengths(aa))))
Using tidyverse packages. Place the list in a nested data frame. Extract the name
for each vector in the list. Unnest the data frame. Give a row index i
for each element in each vector, spread the data in wide format
aa <- list(A = c(1, 3, 4), B = c(3, 5, 7, 7, 8))
library(tidyverse)
data_frame(data = aa) %>%
group_by(name = names(data)) %>%
unnest() %>%
mutate(i = row_number()) %>%
spread(name, data)
# A tibble: 5 x 3
i A B
* <int> <dbl> <dbl>
1 1 1 3
2 2 3 5
3 3 4 7
4 4 NA 7
5 5 NA 8
Make this function:
listToDF <- function(aa){
sapply(aa, "length<-", max(lengths(aa)))
}
Then use it, simply:
listToDF(aa)