To check if a vector contains all the items of another vector in R, you can use the all
function combined with the %in%
operator.
In this example,
vector1
with a set of numerical values.vector2
with a different set of numerical values.all
function combined with the %in%
operator to check if all elements of vector2
are present in vector1
. The %in%
operator returns a logical vector indicating if there is a match or not for its left operand in its right operand.all
function checks if all values in the logical vector are TRUE
. If all elements of vector2
are in vector1
, it returns TRUE
; otherwise, it returns FALSE
.print
function.vector1 <- c(1, 2, 3, 4, 5)
vector2 <- c(2, 3, 4)
result <- all(vector2 %in% vector1)
print(result)
TRUE
In this example,
main_vector
with a series of character strings.sub_vector
with a subset of character strings.all
function combined with the %in%
operator to check if all elements of sub_vector
are present in main_vector
. The %in%
operator returns a logical vector indicating the presence of each element of sub_vector
in main_vector
.all
function checks if every value in this logical vector is TRUE
. If all elements of sub_vector
exist in main_vector
, it will return TRUE
. Otherwise, it will return FALSE
.print
function.main_vector <- c("apple", "banana", "cherry", "date", "fig")
sub_vector <- c("banana", "cherry", "date")
result <- all(sub_vector %in% main_vector)
print(result)
TRUE
In this example,
primary_vector
with a list of mixed data types including numbers and strings.secondary_vector
with some elements that are not present in primary_vector
.all
function combined with the %in%
operator to check if all elements of secondary_vector
are present in primary_vector
. The %in%
operator returns a logical vector for each element of secondary_vector
indicating if it is found in primary_vector
.all
function checks this logical vector to see if all values are TRUE
. Since not all elements of secondary_vector
are in primary_vector
, it returns FALSE
.print
function.primary_vector <- c(10, 20, 30, "apple", "banana")
secondary_vector <- c(20, "banana", "cherry")
result <- all(secondary_vector %in% primary_vector)
print(result)
FALSE
In this tutorial, we learned How to check if a Vector contains all the items of Another Vector in R language with well detailed examples.