How to group set of data.frame objects in nested list with different order?

我的未来我决定 提交于 2019-12-02 04:10:52

Here is a twice nested for loop that creates the desired structure. There is likely a more efficient method.

# put the nested lists into a list:
myList <- list(res_1, res_2, res_3)
# make a copy of the list to preserve the structure for the new list
myList2 <- myList

for(i in seq_len(length(myList))) {
  # get ordering of inner list names
  myOrder <- rank(names(myList[[c(i,2)]]))

  for(j in seq_len(length(myList[[i]]))) {
    for(k in seq_len(length(myList[[c(i, j)]]))) {
      # reorder content
      myList2[[c(myOrder[k], j, i)]] <- myList[[c(i, j, k)]]
      # rename element
      names(myList2[[c(myOrder[k], j)]])[i] <- names(myList[[c(i, j)]])[k]
    }
  }
}

If desired, you could extract the list items after the loops.

The key to this solution is the realization that if you put these lists into a list, the result can be achieved by selectively reversing the indices of the list items. By selectively, I mean that I incorporate rank on the data.frame names to find the proper order for the inner-most loop.

In addition to reordering the data.frames as desired, I included a line to properly reset the names within the list.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!