Home » How to Filter a Vector in R (4 Examples)

How to Filter a Vector in R (4 Examples)

by Erma Khan

You can use the following methods to filter a vector in R:

Method 1: Filter for Elements Equal to Some Value

#filter for elements equal to 8
x[x == 8]

Method 2: Filter for Elements Based on One Condition

#filter for elements less than 8
x[x 

Method 3: Filter for Elements Based on Multiple Conditions

#filter for elements less than 8 or greater than 12
x[(x  12)]

Method 4: Filter for Elements in List

#filter for elements equal to 2, 6, or 12
x[x %in% c(2, 6, 12)]

The following examples show how to use each method in practice.

Example 1: Filter for Elements Equal to Some Value

The following code shows how to filter a vector in R for elements that are equal to 8:

#create vector
x #filter for elements equal to 8
x[x == 8]

[1] 8 8 8

We can just as easily filter for elements that are not equal to 8:

#create vector
x #filter for elements not equal to 8
x[x != 8]

[1]  1  2  2  4  6 12 15

Example 2: Filter for Elements Based on One Condition

The following code shows how to filter a vector in R for elements that are less than 8:

#create vector
x #filter for elements less than 8
x[x 

Example 3: Filter for Elements Based on Multiple Conditions

The following code shows how to filter a vector in R for elements that are less than 8 or greater than 12:

#create vector
x #filter for elements less than 8
x[(x  12)]

[1]  1  2  2  4  6 15

Example 4: Filter for Elements in List

The following code shows how to filter a vector in R for elements that are equal to values in a list:

#create vector
x 
#filter for elements equal to 2, 6, or 12
x[x %in% c(2, 6, 12)]

[1]  2  2  6 12

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Delete Data Frames in R
How to Delete Multiple Columns in R
How to Append Values to a Vector Using a Loop in R

Related Posts