具有不同列数的嵌套列表到一个data.frame / R语言

时间:2016-10-15 13:13:34

标签: r list nested plyr

我正在寻找更有效的方法,将具有不同列数的嵌套列表组合到一个data.frame中。

我的数据看起来像:

All of it is list of 450 nested lists
: List of 356
.. $ 0 :List of 14
.. ..$ name1: value
.. ..$ name2: value
.. ..# Here can be 10 to 19 columns, but only one column with another nested list
.. ..$ dates: List of 1 # This list is always named "dates" and always contains only 1 nested list
.. .. ..$: list of 8 
.. .. .. ..$dates.name1: value 
.. .. .. ..# Here can be 6 to 8 columns
...
: List of 345
.. $ 1 :List of 19
.. ..$ name1: value
.. ..# Here can be 10 to 19 columns, but only one column with another nested list
.. ..$ dates: List of 1 # This list is always named "dates" and always contains only 1 nested list
.. .. ..$: list of 6 
.. .. .. ..$dates.name1: value
.. .. .. ..$dates.name2: value 
.. .. .. ..# Here can be 6 to 8 columns
...

我来到这个解决方案:

nestedlist <- function(data) {

deep1 <- length(data)
deep2 <- vector()
deep3 <- vector()
mergenested <- list()
output <- list()

for (d1 in 1:deep1) {
    deep2[d1] <- length(data[[d1]])

    for(d2 in 1:deep2[d1]){
        deep3[d2] <- which(names(data[[d1]][[d2]])=="dates") # Find index of value with name "dates" - it's my another nested list
        list1 <- data[[d1]][[d2]][[deep3[d2]]][[1]] # Get data from value named "dates" that has another nested list
        list12 <- data[[d1]][[d2]][-deep3[d2]] # Get data without value named "dates"
        mergenested[[d2]] <- as.data.frame(c(list1,list12)) # Concatenate two list to one list / On each iteration "mergenested" has different number of values
    }
  output[[d1]] <- rbind.fill(mergenested) # rbind.fill is function from library "plyr" // Combine lists with different number of columns
}
exit <- rbind.fill(output) # rbind.fill is function from library "plyr" // Another combine lists with different number of columns
}

我认为缓慢来自: a)循环内循环 - 有没有办法在没有两个循环的情况下完成它? b)我在两个循环中都使用了两次rbind.fill。

有什么建议吗?

0 个答案:

没有答案