Dihan
Dihan

Reputation: 311

Check whether two vectors are subsets

I am trying to check whether there is an integer i in {1, ..., M} such that a_i = 1 and b_i = 0 and an integer j in {1,...,M} such that b_j = 1 and a_j = 0. If this holds, output 1 ( incomparable); otherwise, output 0 ( they are comparable).

I tried this:

a<-c(1,0,1,0)
b<-c(1,0,0,1)
M<-length(a)
incomparable<-function(M, a, b)
{
  for(i in 1:M){
    for(j in 1:M){
    if(a[i]!=b[i] && b[j]!=a[j]) {
      print (1)
    }
    else {
      print(0)
      }
    }
  }
}
incomparable(M,a,b)

> incomparable(M,a,b)
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 1
[1] 1
[1] 0
[1] 0
[1] 1
[1] 1

what I need is just 0 or 1 as my output. How can I fix my code?

Upvotes: 1

Views: 61

Answers (1)

Tyrel Stokes
Tyrel Stokes

Reputation: 146

I believe this works for the conditions you describe.


incomparable <- function(a,b){
cond1 <- sum(a>b) > 0 # Returns true is if there is at least one case such that a_i is 1 and b_i is 0
cond2 <- sum(b>a) > 0 # True if at least one case such that one case with b_i is 1 and a_i is 0
  cond1*cond2
}

##### Check a case where they are incomparable vectors

a<-c(1,0,0,1,0,0,1,0)
b<-c(1,0,0,1,1,0,0,0)

incomparable(a,b)
[1] 1

##### Check case where a = b
a<-c(1,0,0,1)
b<-c(1,0,0,1)
incomparable(a,b)
[1] 0

#### Case where a \subset b
a<-c(1,0,0,0,1,0,1)
b<-c(1,0,0,1,1,0,1)

incomparable(a,b)
[1] 0

### Case where b \subset a
a<-c(1,1,1,0,1,0)
b<-c(1,1,0,0,1,0)

incomparable(a,b)
[1] 0

Upvotes: 3

Related Questions