Converting nested list (unequal length) to data frame [duplicate]
We get the length
of list
element ('indx') by looping with sapply
. In the recent version of R
, we can use lengths
to replace the sapply(.., length)
step. We change the length
of each element to the max
length from the 'indx' (length<-
) and thereby pad NA
values at the end of the list
elements with length less than the max
length. We can rbind
the list
elements, convert to data.frame
and change the column names.
indx <- sapply(lst, length)
#indx <- lengths(lst)
res <- as.data.frame(do.call(rbind,lapply(lst, `length<-`,
max(indx))))
colnames(res) <- names(lst[[which.max(indx)]])
res
# sk ques pval diff imp
#1 10 sfsf 0.05 <NA> <NA>
#2 24 wwww 0.11 0.3 <NA>
#3 24 wwww 0.11 0.3 2
data
lst <- list(structure(c("10", "sfsf", "0.05"), .Names = c("sk", "ques",
"pval")), structure(c("24", "wwww", "0.11", "0.3"), .Names = c("sk",
"ques", "pval", "diff")), structure(c("24", "wwww", "0.11", "0.3",
"2"), .Names = c("sk", "ques", "pval", "diff", "imp")))