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 e
Make this function:
listToDF <- function(aa){
sapply(aa, "length<-", max(lengths(aa)))
}
Then use it, simply:
listToDF(aa)
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