检查列表是否在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
,同样返回all
或any
.我确定有一个内衬,但我看不到.
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)
}