检查列表是否在R中包含另一个列表 [英] Check if list contains another list in R

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

问题描述

我想检查列表(或向量,等效)是否包含在另一个列表中,而不是它的子集.让我们假设我们有

I want to check if a list (or a vector, equivalently) is contained into another one, not if it is a subset of thereof. Let us assume we have

r <- c(1,1)
s <- c(5,2)
t <- c(1,2,5)

该函数的行为如下:

is.contained(r,t) 
[1] FALSE
# as (1,1) is not contained in (1,2,5) since the former 
# contains two 1 whereas the latter only one.

is.contained(s,t)
[1] TRUE

运算符%in%检查子集,因此在两种情况下都将返回TRUE,同样返回allany.我确定有一个内衬,但我看不到.

The operator %in% checks for subsets, hence it would return TRUE in both cases, likewise all or any. I am sure there is a one-liner but I just do not see it.

推荐答案

如何使用循环.我遍历第一个向量,并检查第二个向量中是否存在它.如果它在那里,我将其从第二个向量中删除.然后该过程继续.

How about using a loop. I iterate over the first vector and check if it is present in the second vector. If it is there i remove it from second vector. And the process continues.

is.contained=function(vec1,vec2){
    x=vector(length = length(vec1))
    for (i in 1:length(vec1)) {
        x[i] = vec1[i] %in% vec2
        if(length(which(vec1[i] %in% vec2)) == 0) vec2 else 
            vec2=vec2[-match(vec1[i], vec2)]
    }
    y=all(x==T)
    return(y)
}

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

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