How to reduce (subset) list of lists?

Viewed 120

I have a list of lists like this:

list.ex <- list('a' = c(10,11), 'b' = c(9,10,11), 'c' = c(8,9,10,11), 'd' = c(7,8,9,10,11), 'e' = c(6,7,8,9,10,11), 'f' = c(6,8,9,10,11))

I want to check and remove those lists which are a subset of another list (in the exact order). e.g. In this case I want to reduce list.ex such that we are left with list.ex[[e]] and list.ex[[f]].

1 Answers

is_subsequence determines if a is a subset of b in the same order.

library(tidyverse)

is_subsequence <- function(a, b) {
  str_detect(
    paste0(b, collapse = ","),
    fixed(paste0(a, collapse = ","))
  )
}

matches_other takes a vector and determines if it matches more than one vector in list.ex

matches_other <- function(l) {
  map_lgl(
    list.ex,
    ~is_subsequence(l, .)
  ) %>%
  sum() %>%
  `>`(1)
}

discard is used to remove matches.

list.ex %>%
  discard(matches_other)
#> $e
#> [1]  6  7  8  9 10 11
#> 
#> $f
#> [1]  6  8  9 10 11
Related