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.
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
# 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 –
- Append Element to a List in R
- Get Length of a List in R (With Examples)
- Combine Two or More Lists Into One in R
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.