Vectors are used to store one-dimensional data of the same type in R. In this tutorial, we will look at how to remove the last value from a vector in R with the help of some examples.

## How to remove the last value in a Vector in R?

To remove the last value from a vector in R, you can use the negative index equal to the length of the vector inside the `[]`

notation. You can use the `length()`

function in R to get the length of a vector. The following is the syntax –

# remove last value from vector vec <- vec[-length(vec)]

Note that using a negative index does not modify the vector in place. It simply filters the vector and returns a copy with the value at the given index removed. To modify the original vector, assign the resulting vector to the original vector variable.

You can similarly remove any value using its index from a vector in R.

## Examples

Let’s look at some examples of removing the last value from a vector in R.

First, let’s create a vector with four values and remove the last value using the syntax mentioned above.

# create a vector vec <- c(10, 20, 30, 40) # remove the last element vec <- vec[-length(vec)] # display the vector print(vec)

Output:

[1] 10 20 30

Here, we use negative indexing to remove the value at the index equal to the length of the vector (which is the last value inside the vector). Note that we re-assign the returned vector to the variable `vec`

. You can see that the last value from the original vector is not present in the resulting vector.

Let’s look at another example. This time let’s use a vector with named values.

# create a vector vec <- c("a"=10, "b"=20, "c"=30, "d"=40) # remove the last element vec <- vec[-length(vec)] # display the vector print(vec)

Output:

a b c 10 20 30

You can see that the last value from the original vector was removed.

You might also be interested in –

**Subscribe to our newsletter for more informative guides and tutorials. ****We do not spam and you can opt out any time.**