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.
Method 1: Remove elements using in operator
This operator will select specific elements and uses ! operator to exclude those elements.
Syntax:
vector[! vector %in% c(elements)]
Example:
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)]
Example:
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
Method 2: Using conditions to remove the elements
In this method, the user needs to use the specific conditions accordingly to remove the elements from a given vector.
Syntax:
vector[!condition]
where
- condition: specifies the condition that element be checked
Example:
R
# create a vector vector1= c (1,34,56,2,45,67,89,22,21,38) # display print (vector1) # remove the elements with element greater # than 50 or less than 20 print (vector1[!(vector1 > 50 | vector1 < 20)]) |
Output:
[1] 1 34 56 2 45 67 89 22 21 38 [1] 34 45 22 21 38
Please Login to comment...