To remove an item at a specific index from a vector in R, you can use negative indexing or the setdiff
function.
In this example,
vec
with some integer values.index_to_remove
.vec_new
that includes all elements of vec
except the one at index_to_remove
.vec_new
to see the result.vec <- c(10, 20, 30, 40, 50)
index_to_remove <- 3
vec_new <- vec[-index_to_remove]
print(vec_new)
[1] 10 20 40 50
In this example,
vec
with some integer values.index_to_remove
.setdiff
function to remove the item at the specified index. The setdiff
function returns the difference of two sets.vec_new
that includes all elements of vec
except the one at index_to_remove
by removing the value at that index.vec_new
to see the result.vec <- c(10, 20, 30, 40, 50)
index_to_remove <- 3
vec_new <- setdiff(vec, vec[index_to_remove])
print(vec_new)
[1] 10 20 40 50
In this tutorial, we learned How to Remove Item at a Specific Index from a Vector in R language with well detailed examples.