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 #  "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 #  "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.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may have a look at some of the related tutorials of my website. A selection of articles is listed here:
- Compare Character Strings with Logical Operator Conditionally
- Extract Data Frame Rows that do not Match Logical Condition
- Subset Data Frame Rows Based On Factor Levels
- filter R Function of dplyr Package
- Introduction to R
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.
Statistics Globe Newsletter