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

前端 未结 1 1049
暖寄归人
暖寄归人 2021-01-23 11:48

I have set of data.frame object in nested list, I want to group them by name of data.frame object. Because each nested list, data.frame objects are placed in different order, I

相关标签:
1条回答
  • 2021-01-23 12:01

    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.

    0 讨论(0)
提交回复
热议问题