检查一个向量是否是R中另一个向量的超集 [英] Check if a vector is a superset of another vector in R

查看:75
本文介绍了检查一个向量是否是R中另一个向量的超集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下向量列表:

a <- c(1,2,4,5,6,7,8,9)
b <- c(1,2,4,5)
c <- c(1,2,3,10,11,12,13,14)
d <- c(1,2,3,10,15,16,17,18,19)
e <- c(1,2,3,10,15,16)
f <- list(a,b,c,d,e)

现在,我可以做类似的事情

Right now, I can do something like this

is_subset <- vector()
for(i in 1:length(f)) {
  is_subset <- c(is_subset, all(unlist(f[i]) %in% unlist(f[-i])))
}
f[!is_subset]

并从原始列表中获取一个列表,该列表包含每个矢量,该矢量不是其他任何矢量的子集:

and get a list containing every vector that is not a subset of any other vector from the original list:

[[1]]
[1] 1 2 4 5 6 7 8 9

[[2]]
[1]  1  2  3 10 11 12 13 14

[[3]]
[1]  1  2  3 10 15 16 17 18 19

但是,我真正想要的是对列表进行子集处理,以便它仅包括那些不是列表中其他向量的超集的向量-即所需的输出应如下所示:

However, what I really want is to subset the list so that it includes only those vectors that are not supersets of other vectors from the list -- i.e., the desired output should look like this:

[[1]]
[1] 1 2 4 5

[[2]]
[1]  1  2  3 10 11 12 13 14

[[3]]
[1]  1  2  3 10 15 16

如何在R中做到这一点?

How can I do this in R?

推荐答案

在下面的代码片段中,我使用%in%将列表中的每个向量与其他向量进行了比较.如果每个比较向量的总和不止一次出现非零,则该向量是另一个向量的超集.请注意,我们希望单个比较完全匹配,即向量与自身的比较.

In the code snippet below, I compare each vector in your list against every other vector using %in%. If the sum of each comparison vector comes up non zero more than once, then the vector is a superset of another vector. Note that we expect a single comparison to match exactly, namely the comparison of a vector against itself.

out <- sapply(f, function(x) {
    res <- lapply(f, function(y) {
        return(sum(!(y %in% x)))
    })
    return(sum(res > 0) == length(res) - 1)
})

f[out]
[[1]]
[1] 1 2 4 5

[[2]]
[1]  1  2  3 10 11 12 13 14

[[3]]
[1]  1  2  3 10 15 16

演示

这篇关于检查一个向量是否是R中另一个向量的超集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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