rmapplycombn

How to see which element (of length x) in a list is contained in which other element (of length x+1) of that list?


Say I have the following list:

unlist(mapply(combn, list(1:3), seq_along(1:3), simplify = FALSE), recursive = FALSE)

Now, I want to know for each element of length x in the list, in which other elements of length x+1 it is contained. Preferably, it returns a data frame, where the first column gives the index of an element, and the second column gives the index of other elements in which it is contained.

For the example above, it would need to give me:

tibble::tribble(
  ~a, ~b,
  1,  4,
  1,  5,
  2,  4,
  2,  6,
  3,  5,
  3,  6,
  4,  7,
  5,  7,
  6,  7
)

Solution

  • You can use a double sapply to compare each pair of vectors in your list. This will return a logical square matrix. If you then call which with arr.ind = TRUE and exclude the diagonal, you will have your desired data frame.

    Here's a full reprex:

    mylist <- unlist(mapply(combn, list(1:3), seq_along(1:3), simplify = FALSE), 
                     recursive = FALSE)
    
    mat <- which(t(sapply(mylist, function(x) sapply(mylist, function(y) {
      all(x %in% y) & length(y) == length(x) + 1
      }))), arr.ind = TRUE)
    
    setNames(as.data.frame(mat), c("a", "b"))[order(mat[,1]),]
    #>   a b
    #> 1 1 4
    #> 3 1 5
    #> 2 2 4
    #> 5 2 6
    #> 4 3 5
    #> 6 3 6
    #> 7 4 7
    #> 8 5 7
    #> 9 6 7