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
Additional Resources
How to Delete Data Frames in R
How to Delete Multiple Columns in R
How to Append Values to a Vector Using a Loop in R