How to create all combinations from a nested list while preserving the structure using R?

前端 未结 4 1917
盖世英雄少女心
盖世英雄少女心 2021-01-04 07:10

Given a nested list, how to create all possible lists from its elements, while preserving the structure of the nested list?

Nested list:



        
4条回答
  •  没有蜡笔的小新
    2021-01-04 07:45

    Combining Ben Nutzer's brilliant answer and Joris Chau's brilliant comment, the answer will become a one-liner:

    apply(expand.grid(data.frame(l)), 1L, relist, skeleton = rapply(l, head, n = 1L, how = "list")) 
    

    It creates a list of lists with as many elements as rows returned by expand.grid(). The result is better visualised by the output of str():

    str(apply(expand.grid(data.frame(l)), 1L, relist, skeleton = rapply(l, head, n = 1L, how = "list")))
    
    List of 16
     $ :List of 3
      ..$ a:List of 1
      .. ..$ b: num 1
      ..$ c:List of 1
      .. ..$ d:List of 2
      .. .. ..$ e: num 3
      .. .. ..$ f: num 5
      ..$ g: num 7
     $ :List of 3
      ..$ a:List of 1
      .. ..$ b: num 2
      ..$ c:List of 1
      .. ..$ d:List of 2
      .. .. ..$ e: num 3
      .. .. ..$ f: num 5
      ..$ g: num 7
    ...
    ...
    ...
     $ :List of 3
      ..$ a:List of 1
      .. ..$ b: num 2
      ..$ c:List of 1
      .. ..$ d:List of 2
      .. .. ..$ e: num 4
      .. .. ..$ f: num 6
      ..$ g: num 7
    

提交回复
热议问题