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.
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
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
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
Remove element from vector by index
To remove elements from a vector by index in R, we can use negative indexing or the subsetting technique. Here’s an example.
R
# Create a vector vector1 <- c (1, 34, 56, 2, 45, 67, 89, 22, 21, 38) # Display the original vector print ( "Original Vector:" ) print (vector1) # Remove elements by index vector1 <- vector1[- c (3,5)] # Display the modified vector print ( "Modified Vector:" ) print (vector1) |
Output:
[1] "Original Vector:"
[1] 1 34 56 2 45 67 89 22 21 38
[1] "Modified Vector:"
[1] 1 34 2 67 89 22 21 38
Contact Us