Delete Item at Specific Index from R Vector

To delete an item at specific index from R Vector, pass the negated index as a vector in square brackets after the vector. We can also delete multiple items from a vector, based on index.

In this tutorial, we will learn how to delete an item from vector at specific index.

Syntax

The syntax to delete items at given indices from a vector x is

</>
Copy
x[-indices]

where indices is a vector.

Return Value

The above expression returns a new vector formed with the vector x and the items at specified indices removed.

The original vector x remains unchanged.

Examples

Delete One Element

In the following program, we take an integer vector with five elements. We remove the fourth item.

Example.R

</>
Copy
x <- c(10, 20, 30, 40, 50)
indices <- c(4)
result <- x[-indices]
print(result)

Output

[1] 10 20 30 50

Delete Multiple Elements

In the following program, we take an integer vector with five elements. We remove the second and third elements.

Example.R

</>
Copy
x <- c(10, 20, 30, 40, 50)
indices <- c(2, 3)
result <- x[-indices]
print(result)

Output

[1] 10 40 50

Conclusion

In this R Tutorial, we learned how to delete items from a vector at specified index or indices, with the help of examples.