- Published on
How to Remove Specific Elements from a Vector in R
- Authors

- Name
- hwahyeon
This article explains how to remove all occurrences of specific elements from a vector in R. To understand this method, we first need to look at the %in% operator.
The %in% operator checks whether a value is included in a given vector. For example, consider the following code.
x <- c("A", "B", "C", "B", "C")
x %in% "C"
The result is as follows.
[1] FALSE FALSE TRUE FALSE TRUE
This result shows whether each element of x is "C". "A" and "B" are not "C", so they return FALSE, while "C" returns TRUE.
In R, square brackets [] are used to select elements from a vector. For example, x[1] selects the first element of x, and x[c(1, 3)] selects the first and third elements.
x <- c("A", "B", "C", "B", "C")
x[1]
The result is as follows.
[1] "A"
x[c(1, 3)]
The result is as follows.
[1] "A" "C"
You can also put a logical vector made up of TRUE and FALSE values inside the square brackets. In that case, only the elements in the TRUE positions are selected.
x[c(TRUE, FALSE, TRUE, FALSE, FALSE)]
The result is as follows.
[1] "A" "C"
Using this logical vector, we can select only the elements that meet a certain condition. For example, the code below selects only the elements of x that are "C".
x[x %in% "C"]
The result is as follows.
[1] "C" "C"
However, what we want is not to select "C", but to remove it. To do this, we use the ! operator, which reverses logical values.
x <- c("A", "B", "C", "B", "C")
x <- x[!(x %in% "C")]
The result is as follows.
[1] "A" "B" "B"
Here, !(x %in% "C") turns the positions where the value was "C" into FALSE, and the positions where the value was not "C" into TRUE. As a result, only the elements that are not "C" remain.
If you want to remove two or more elements, you can put the elements to be removed after %in% as a vector. In the example below, "B" and "C" are both removed from x.
x <- c("A", "B", "C", "B", "C")
x <- x[!(x %in% c("B", "C"))]
The result is as follows.
[1] "A"
Here, x %in% c("B", "C") checks whether each element of x is included in "B" or "C". By adding !, we select only the elements that are not "B" or "C", so only "A" remains.
This method can be used not only with character vectors, but also with numeric vectors.
x <- c(1, 2, 2, 2, 7)
x <- x[!(x %in% c(1, 2))]
The result is as follows.
[1] 7