To remove a specific item from a vector in R, you can use logical indexing or the setdiff
function.
In this example,
vec
with some integer values.item_to_remove
.TRUE
for all elements not equal to item_to_remove
and FALSE
otherwise.vec <- c(10, 20, 30, 40, 50)
item_to_remove <- 30
vec_new <- vec[vec != item_to_remove]
print(vec_new)
[1] 10 20 40 50
In this example,
vec
with some integer values.item_to_remove
.setdiff
function to remove the specified item. The setdiff
function returns the difference between the original vector and a vector containing the item to remove.vec_new
that includes all elements of vec
except the one specified in item_to_remove
.vec <- c(10, 20, 30, 40, 50)
item_to_remove <- 30
vec_new <- setdiff(vec, item_to_remove)
print(vec_new)
[1] 10 20 40 50
In this tutorial, we learned How to Remove Specific Item from a Vector in R language with well detailed examples.