How to Filter a Vector in R

• Last Updated : 03 Sep, 2021

In this article, we are going to discuss how to filter a vector in the R programming language.

Filtering a vector means getting the values from the vector by removing the others, we can also say that getting the required elements is known as filtering.

Method 1: Using %in%

Here we can filter the elements in a vector by using the %in% operator

Syntax:

vec[vec %in% c(elements)]

where

• vec is the input vector
• elements are the vector elements that we want to get

Example:  R program to filter the vector by getting only some values

R

 `# create a vector with id and names``vector=``c``(1,2,3,4,5,``"sravan"``,``"boby"``,``"ojaswi"``,``"gnanesh"``,``"rohith"``)` `# display vector``print``(vector)` `print``(``"======="``)` `# get the data  - "sravan","rohith",3 from``# the vector``print``(vector[vector %``in``% ``c``(``"sravan"``,``"rohith"``,3)])` `print``(``"======="``)` `# get the data  - "sravan","ojaswi",3,1,2 from``# the vector``print``(vector[vector %``in``% ``c``(``"sravan"``,``"ojaswi"``,3,1,2)])` `print``(``"======="``)` `# get the data  - 1,2,3,4,5 from the vector``print``(vector[vector %``in``% ``c``(1,2,3,4,5)])`

Output:

[1] “1”       “2”       “3”       “4”       “5”       “sravan”  “boby”

[8] “ojaswi”  “gnanesh” “rohith”

[1] “=======”

[1] “3”      “sravan” “rohith”

[1] “=======”

[1] “1”      “2”      “3”      “sravan” “ojaswi”

[1] “=======”

[1] “1” “2” “3” “4” “5”

Method 2: Using Index

We can also specify the condition from the index operator.

Syntax:

vector[condition(s)]

where the vector is the input vector and condition defines the condition to follow for filtering.

Example: R program to filter vector using the conditions

R

 `# create a vector with id and names``vector=``c``(1,2,3,4,5,``"sravan"``,``"boby"``,``"ojaswi"``,``"gnanesh"``,``"rohith"``)` `# display vector``print``(vector)` `print``(``"======="``)` `# get the data where element not equal to 1``print``(vector[vector != 1])` `print``(``"======="``)` `# get the data where element  equal to 1``print``(vector[vector == 1])`

Output:

[1] “1”       “2”       “3”       “4”       “5”       “sravan”  “boby”

[8] “ojaswi”  “gnanesh” “rohith”

[1] “=======”

[1] “2”       “3”       “4”       “5”       “sravan”  “boby”    “ojaswi”

[8] “gnanesh” “rohith”

[1] “=======”

[1] “1”

My Personal Notes arrow_drop_up