Remove elements using in operator

This operator will select specific elements and uses ! operator to exclude those elements.

Syntax:

vector[! vector %in% c(elements)]

In this example, we will be using the in operator to remove the elements in the given vector in the R programming language.

R




# create a vector
vector1=c(1,34,56,2,45,67,89,22,21,38)
 
# display
print(vector1)
 
# remove the elements
print(vector1[! vector1%in% c(34,45,67)])


Output:

[1]  1 34 56  2 45 67 89 22 21 38

[1]  1 56  2 89 22 21 38

Note: We can also specify the range of elements to be removed.

Syntax:

vector[! vector %in% c(start:stop)]

R




# create a vector
vector1 = c(1, 34, 56, 2, 45, 67, 89, 22, 21, 38)
 
# display
print(vector1)
 
# remove the elements
print(vector1[! vector1 %in% c(1:50)])


Output:

[1]  1 34 56  2 45 67 89 22 21 38

[1] 56 67 89

How to Remove Specific Elements from Vector in R?

In this article, we will discuss how to remove specific elements from vectors in R Programming Language.

Similar Reads

Remove elements using in operator

This operator will select specific elements and uses ! operator to exclude those elements....

Using conditions to remove the elements

...

Remove element from vector by index

...