保留在列表中没有适当子集的元素(从向量列表中)(在R中) [英] Keeping elements (from list of vectors) that do not have a proper subset within that list (in R)

查看:38
本文介绍了保留在列表中没有适当子集的元素(从向量列表中)(在R中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

适当子集:集合S的适当子集S'是严格包含在S中的子集,因此排除了S本身(请注意,我也排除了空集合).

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).

假设您在列表中具有以下向量:

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)

我的目标是只保留列表中没有适当子集的向量,在此示例中为a,b和c.以下代码是我的解决方案,

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. 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.

推荐答案

一个 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

仅保留目标向量:

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

这篇关于保留在列表中没有适当子集的元素(从向量列表中)(在R中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆