How to Use the is.element() Function in R

The is.element() function in R is “used to check the presence of element(s) of an object in another object”.

Syntax

is.element(element, data)

Parameters

  1. element: A vector containing the elements you want to check for their presence in the data.
  2. data: A vector in which you want to check for the presence of the elements in the element.

Return value

The is.element() function returns a logical value (true or false), suggesting whether the element appears in y.

Example 1

# Create a sample vector
main_vector <- c(2, 4, 6, 8, 10)

# Define the elements you want to check
elements_to_check <- c(4, 7)

# Check if the elements are present in the vector
element_found <- is.element(elements_to_check, main_vector)

# Print the result
print(element_found)

Output

[1] TRUE FALSE

In this example, the is.element() function checks if the elements in the elements_to_check vector are present in the main_vector.

The result is a logical vector with TRUE for the elements found in main_vector and FALSE for those not found.

Example 2

df_x <- data.frame(
  x1 = c(51, 31, 71),
  x2 = c(11, 41, 21)
)

# Data frame 2
df_y <- data.frame(
  y1 = c(22, 3, 24),
  y2 = c(51, 31, 71),
  y3 = c(23, 24, 25)
)

# Calling is.element() Function
is.element(df_x, df_y)
is.element(df_y, df_x)

Output

[1] TRUE FALSE
[1] FALSE TRUE FALSE

That’s it.

Leave a Comment