Skip to Content

Remove Last Value From a List in R

In this tutorial, we will look at how to remove the last value from a list in R with the help of some examples.

How to remove the last value in a List in R?

You can remove the last value from a list in R by setting the value at the last index (same as the list’s length) to NULL. You can use the length() function to get the length of a list in R. The following is the syntax –

# remove last value from list
ls[length(ls)] <- NULL

You can also use the above syntax to remove any value from a list using its index. Just replace length(ls) with the index of the value you want to remove from the list.

Examples

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

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

# create a list
ls <- list("a", "b", "c", "d")
# remove the last element
ls[length(ls)] <- NULL
# display the list
print(ls)

Output:

[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

Here, we create a list of four character values and then set the value at the last index in the list (which we get using the length() function) to NULL. We then print the list. You can see that the list now does not have the last value from the original list.

Alternatively, you can use negative indexing to exclude values at certain indexes (for our use case, remove the last value). Note that this does not modify the list in place. To modify the original list, assign the result from the negative indexing to the original list variable.

Let’s remove the last element from the same list used in the example above. A list of four character values.

# create a list
ls <- list("a", "b", "c", "d")
# remove the last element
ls <- ls[-length(ls)]
# display the list
print(ls)

Output:

[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

You can see that we get the same result as above.

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.


Author

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.