Convert a nested list (unequal length) to a data frame

I have a nested list; for some indices, some variables are missing.

[[1]]
    sk   ques   pval 
  "10" "sfsf" "0.05" 

[[2]]
    sk   ques   pval   diff 
 "24" "wwww" "0.11"  "0.3" 

[[3]]
    sk   ques   pval   diff    imp 
  "24" "wwww" "0.11"  "0.3"    "2" 

How can I convert this to a data frame, where for the first row is the data $ diff [1] = NA? Above the case will be a data frame with 5 variables and 3 observations.

The number of variables in the data frame will be the number of unique names in the list items, and missing values ​​within the list will be replaced by NA.

Thank,

EDIT: data format

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")))
0
source share
1 answer

length list ('indx') sapply. R lengths sapply(.., length). length max "indx" (length<-) , , NA list max, rbind list, data.frame .

 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

 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")))
+8

Source: https://habr.com/ru/post/1665754/


All Articles