w3resource

Test Whether a Vector contains a specified element in R Programming


Write a R program to test whether a given vector contains a specified element.

Sample Solution :

R Programming Code :

# Create a numeric vector 'x' with elements 10, 20, 30, 25, 9, and 26
x = c(10, 20, 30, 25, 9, 26)

# Print a message indicating the display of the original vector
print("Original Vectors:")

# Print the contents of vector 'x'
print(x)

# Print a message indicating the test for the presence of the element 25
print("Test whether above vector contains 25:")

# Test if the vector 'x' contains the element 25 and print the result
print(is.element(25, x))

# Print a message indicating the test for the presence of the element 56
print("Test whether above vector contains 56:")

# Test if the vector 'x' contains the element 56 and print the result
print(is.element(56, x))

Output:

[1] "Original Vectors:"
[1] 10 20 30 25  9 26
[1] "Test whether above vector contains 25:"
[1] TRUE
[1] "Test whether above vector contains 56:"
[1] FALSE                         

Explanation:

  • x = c(10, 20, 30, 25, 9, 26): Creates a numeric vector x with the elements 10, 20, 30, 25, 9, and 26.
  • print("Original Vectors:"): Prints the label "Original Vectors:" to indicate that the following output will show the vector x.
  • print(x): Prints the contents of vector x.
  • print("Test whether above vector contains 25:"): Prints the label "Test whether above vector contains 25:" to indicate that the following output will show whether the vector x contains the element 25.
  • print(is.element(25, x)): Checks if the element 25 is present in vector x and prints the result, which will be TRUE if it is present.
  • print("Test whether above vector contains 56:"): Prints the label "Test whether above vector contains 56:" to indicate that the following output will show whether the vector x contains the element 56.
  • print(is.element(56, x)): Checks if the element 56 is present in vector x and prints the result, which will be FALSE if it is not present.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to sort a Vector in ascending and descending order.
Next: Write a R program to count the specific value in a given vector.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.