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
.
We can use all
with %in%
all(A %in% B)
#[1] TRUE
all(B %in% A)
#[1] FALSE
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With