Transpose a List of Lists

后端 未结 5 2011
我寻月下人不归
我寻月下人不归 2020-12-01 23:32

I have a list which contains list entries, and I need to transpose the structure. The original structure is rectangular, but the names in the sub-lists do not match.

5条回答
  •  独厮守ぢ
    2020-12-02 00:04

    I found myself with this problem but I needed a solution that kept the names of each element. The solution I came up with should also work when the sub lists are not all the same length.

    invertList = function(l){
      elemnames = NULL
      for (i in seq_along(l)){
        elemnames = c(elemnames, names(l[[i]]))
      }
    
      elemnames = unique(elemnames)
    
      res = list()
      for (i in seq_along(elemnames)){
        res[[elemnames[i]]] = list()
        for (j in seq_along(l)){
          if(exists(elemnames[i], l[[j]], inherits = F)){
            res[[i]][[names(l)[j]]] = l[[names(l)[j]]][[elemnames[i]]]
          }
        }
      }
      res
    }
    

提交回复
热议问题