Reputation: 311
Say, I have two vectors:
A <- c(1,0,0,1,0,0,0)
and
B <- c(1,0,0,1,0,1,1)
By my definition, A is subset of B, (both vectors contain binary values only) if and only if
A
and B
have the same length and thus have the same number of elements;A
should have either 0
or 1
at all places wherever B
has 1
A
can have only 0
s at all places where B
has 0
s.Now I wish to write a code that would verify something within the lines of
if(A subset of B){}
Thank you!
Upvotes: 1
Views: 862
Reputation: 39737
You can test if length
is ==
and if any
values of A have a 1
on positions where B has a 1
and combine the conditions with &&
.
length(A) == length(B) && any(A[B==1]==1)
#[1] TRUE
Fulfilling the condition in the original question: A and B have the same length and thus have the same number of elements; yet, A is a subset of B, since A has elements 1 in the same place as B.
To fulfill:
A
and B
have the same length and thus have the same number of elements;A
should have at least one 1
at places wherever B
has 1
A
can have only 0
s at all places where B
has 0
s.length(A) == length(B) && any(A[B==1]==1) && all(A[B==0]==0)
To fulfill:
A
and B
have the same length and thus have the same number of elements;A
can have only 0
s at all places where B
has 0
s.length(A) == length(B) && all(A[B==0]==0)
Upvotes: 2
Reputation: 5232
First condition checks for same length, second checks that A doesn't have 1 on position on which B has 0.
if(length(A) == length(B) && all(B - A >= 0)) TRUE else FALSE
Upvotes: 1