How do you remove specific elements from a vector in R?

In R, you can remove specific elements from a vector by using the subset() function. This function allows you to subset a vector based on certain criteria and remove the elements that match the criteria. You can also use the subset() function to remove multiple elements in one go. Another option is to use the negative indexing approach, which allows you to delete the elements at certain indices by using negative indices. Finally, you can also use the which() function to find the indices of the elements you want to remove and then use the negative indexing approach to delete them.


You can use the following basic syntax to remove specific elements from a vector in R:

#remove 'a', 'b', 'c' from my_vector
my_vector[! my_vector %in% c('a', 'b, 'c')]

The following examples show how to use this syntax in practice.

Example 1: Remove Elements from Character Vector 

The following code shows how to remove elements from a character vector in R:

#define vector
x <- c('Mavs', 'Nets', 'Hawks', 'Bucks', 'Spurs', 'Suns')

#remove 'Mavs' and 'Spurs' from vector
x <- x[! x %in% c('Mavs', 'Spurs')]

#view updated vector
x

[1] "Nets"  "Hawks" "Bucks" "Suns" 

Notice that both ‘Mavs’ and ‘Spurs’ were removed from the vector.

Example 2: Remove Elements from Numeric Vector 

The following code shows how to remove elements from a numeric vector in R:

#define numeric vector
x <- c(1, 2, 2, 2, 3, 4, 5, 5, 7, 7, 8, 9, 12, 12, 13)

#remove 1, 4, and 5
x <- x[! x %in% c(1, 4, 5)]

#view updated vector
x

[1]  2  2  2  3  7  7  8  9 12 12 13

Notice that every occurrence of the values 1, 4, and 5 were removed from the vector.

We can also specify a range of values that we’d like to remove from the numeric vector:

#define numeric vector
x <- c(1, 2, 2, 2, 3, 4, 5, 5, 7, 7, 8, 9, 12, 12, 13)

#remove values between 2 and 10
x <- x[! x %in% 2:10]

#view updated vector
x

[1]  1 12 12 13

Notice that every value between 2 and 10 was removed from the vector.

We can also remove values greater or less than a specific number:

#define numeric vector
x <- c(1, 2, 2, 2, 3, 4, 5, 5, 7, 7, 8, 9, 12, 12, 13)

#remove values less than 3 or greater than 10
x <- x[!(x < 3 | x > 10)]

#view updated vector
x

[1] 3 4 5 5 7 7 8 9

x