Test if Vector Contains Given Element in R (Example)

 

This tutorial explains how to test if a vector contains a certain element in R.

I will show a step by step example, which is structured as follows:

Here’s the step-by-step process:

 

Creation of Example Vector

In this tutorial, we will use the following example vector:

vec <- c("AAA", "Hello", "12345", "X")    # Create example vector

Our example vector contains several character strings stored in the data object vec.

 

Test if Vector Contains Given Element

Now, we can test whether this example vector contains a certain element. For this test, we can use the %in% operator as follows:

"AAA" %in% vec                            # Test if AAA is in vector
# TRUE

The application of the %in% operator consists of three parts:

  1. Part 1: Specify the element you are searching for (i.e. “AAA)
  2. Part 2: Write down the R syntax %in%
  3. Part 3: Specify the name of the data you want to search in (i.e. vec)

As you can see based on the previous R code, the %in% operator returns a logical value (i.e. TRUE or FALSE) to the RStudio console. In our example, the value TRUE was returned, indicating that the input value “AAA” exists within the vector vec.

Note that the %in% operator tests for exact matches. If we search for a partial match, the RStudio console returns FALSE:

"A" %in% vec                              # Test if A is in vector
# FALSE

 

Video & Further Resources

Do you want to learn more about the testing whether some specified values are included in a vector or column? Then you could have a look at the following R programming video that I have recently published on my YouTube channel. In the video, I am explaining the example of this tutorial in more detail:

 

 

In addition, you may also have a look at the other R tutorials of this site. You can find some related tutorials below:

At this point of the tutorial, you should be able to check if a value is included in certain data in R (or RStudio). In case you have any further comments or questions, please let me know in the comments below.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top