How to Filter a Vector in R (Example)


In this post you’ll learn how to subset the elements of a vector object in the R programming language.

Table of contents:

It’s time to dive into the example:


Construction of Example Data

Let’s first create some exemplifying data in R:

vec <- c("a", "b", "a", "c", "d")           # Create example vector
vec                                         # Print example vector
# [1] "a" "b" "a" "c" "d"

The previous output of the RStudio console shows that the example data is a vector object consisting of five alphabetical vector elements.


Example: Subset Vector Object Using %in% Operator

The following R syntax shows how to extract certain elements of our vector based on a logical condition using the %in% operator.

Have a look at the following R code:

vec_filter1 <- vec[vec %in% c("a", "c")]    # Filter vector
vec_filter1                                 # Print updated vector
# [1] "a" "a" "c"

The previous R syntax has created a new vector object called vec_filter1. This vector object consists only of values that fulfilled the logical condition of the previous R code, i.e. the letters “a” and “c”.


Video & Further Resources

Do you want to learn more about filtering vectors and arrays? Then I recommend watching the following video that I have published on my YouTube channel. I’m explaining the R programming codes of this article in the video.



In addition, you may have a look at some of the related tutorials of my website. A selection of articles is listed here:


At this point you should know how to filter vectors in the R programming language. Please let me know in the comments, if you have any additional questions.


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.