简体   繁体   English

保留在该列表中没有适当子集的元素(来自向量列表)(在 R 中)

[英]Keeping elements (from list of vectors) that do not have a proper subset within that list (in R)

Proper subset: A proper subset S' of a set S is a subset that is strictly contained in S and so excludes S itself (note I am also excluding the empty set).真子集:集合 S 的真子集 S' 是严格包含在 S 中的子集,因此排除 S 本身(注意我也排除了空集)。

Suppose you have the following vectors in a list:假设您在列表中有以下向量:

a = c(1,2)
b = c(1,3)
c = c(2,4)
d = c(1,2,3,4)
e = c(2,4,5)
f = c(1,2,3)

My aim is to keep only vectors which have no proper subset within the list, which in this example would be a, b and c.我的目标是只保留列表中没有适当子集的向量,在这个例子中是 a、b 和 c。 The following code is my solution,以下代码是我的解决方案,

possibilities = list(a,b,c,d,e,f)

final.list <- possibilities

for (i in possibilities) {
  for (j in rev(possibilities)) {
    if (all(i %in% j) & !all(j %in% i)) {
      final.list <- final.list[!(final.list %in% list(j))]
    } else {
      final.list <- final.list
    }
  }
}

which gives the intended output, though I am concerned with the scalability of this approach.这给出了预期的输出,尽管我担心这种方法的可扩展性。 Does anyone have an idea for a more efficient approach?有没有人有更有效的方法的想法? Thanks!谢谢!

* Note that for my true purpose the length of the possibilities list--and its sub-vectors--can grow quite large. * 请注意,就我的真正目的而言,可能性列表的长度——及其子向量——可能会变得非常大。

One purrr option could be:一种purrr选项可能是:

map2(.x = possibilities,
     .y = seq_along(possibilities),
     ~ !any(map_lgl(possibilities[-.y], function(z) all(z %in% .x))))

[[1]]
[1] TRUE

[[2]]
[1] TRUE

[[3]]
[1] TRUE

[[4]]
[1] FALSE

[[5]]
[1] FALSE

[[6]]
[1] FALSE

To keep only the target vectors:只保留目标向量:

keep(possibilities,
     map2_lgl(.x = possibilities,
              .y = seq_along(possibilities),
              ~ !any(map_lgl(possibilities[-.y], function(z) all(z %in% .x)))))

[[1]]
[1] 1 2

[[2]]
[1] 1 3

[[3]]
[1] 2 4

Here is a base R option这是一个基本的 R 选项

final.list <- subset(
  possibilities,
  sapply(
    seq_along(possibilities),
    function(k) {
      !any(sapply(
        possibilities[-k],
        function(v) all(v %in% possibilities[[k]]) & length(v) < length(possibilities[[k]])
      ))
    }
  )
)

which gives这使

> final.list
[[1]]
[1] 1 2

[[2]]
[1] 1 3

[[3]]
[1] 2 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM