Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if set A is subset of set B in R? [duplicate]

Tags:

r

set

subset

I have two sets A and B. I want to check if set A is a subset of set B. I have tried I am aware of the set operation in R. I have tried intersect, union, setdiff. However, non of them were helpful. For example,

A = c(1, 2, 3, 4)

B = c(1, 2, 3, 4, 5)

I am looking for a function that returns TRUE or FALSE. I have used A %in% B and compare the sum and length, which does the same job. But I feel like there is a beter way of doing this.

length(A %in% B) == sum(A %in% B) returns TRUE and length(B %in% A) == sum(B %in% A) returns FALSE.

like image 410
Chris Avatar asked Jun 06 '16 11:06

Chris


2 Answers

We can use all with %in%

all(A %in% B)
#[1] TRUE

all(B %in% A)
#[1] FALSE
like image 63
akrun Avatar answered Oct 05 '22 03:10

akrun


Another way around, to check if A is a subset of B

setequal(intersect(A,B), A)
# [1] TRUE

to check if B is a subset of A

setequal(intersect(A,B), B)
# [1] FALSE
like image 26
989 Avatar answered Oct 05 '22 04:10

989