Carl
Carl

Reputation: 311

How to check whether a vector is subset of another one in R?

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

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

Answers (2)

GKi
GKi

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 0s at all places where B has 0s.
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 0s at all places where B has 0s.
length(A) == length(B) && all(A[B==0]==0)

Upvotes: 2

det
det

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

Related Questions