Remove Last N Elements of Vector in R (2 Examples)

 

In this tutorial, I’ll illustrate how to delete the last N elements of a vector object in the R programming language.

Table of contents:

It’s time to dive into the examples…

 

Construction of Example Data

I’ll use the following data as basement for this R programming tutorial:

vec <- letters[1:10]        # Create example vector
vec                         # Print example vector
#  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

The previous output of the RStudio console shows that our example data is a vector object with ten elements. The items of our example vector reflect an alphabetical range from “a” to “j”.

 

Example 1: Delete the Very Last Element of a Vector

Example 1 illustrates how to remove only the very last element from our vector.

For this, we can use the head function as shown below:

head(vec, - 1)              # Remove last element
# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i"

As you can see, we have removed the last element (i.e. “j”) from our example vector.

Do you want to extract even more elements from our vector? Then keep on reading!

 

Example 2: Delete the Last N Elements of a Vector

In Example 2, I’ll show how to drop N elements at the end of our vector.

The only difference compared to Example 1 is that we have to set the negative number within the head function to the number of elements that we want to get rid of.

In this example, we’ll remove five elements:

head(vec, - 5)              # Remove last N elements
# [1] "a" "b" "c" "d" "e"

Have a look at the previous output. We have kept only the first five elements (i.e. the last five elements have been deleted).

 

Video, Further Resources & Summary

If you need further information on the content of this article, I recommend having a look at the following video of my YouTube channel. In the video, I’m explaining the R code of this post in RStudio.

 

The YouTube video will be added soon.

 

In addition, you may want to have a look at the other tutorials on Statistics Globe:

 

In summary: On this page, I have shown how to remove the values at the end of a vector or array object in R programming. Please tell me about it in the comments section, if you have further questions. Furthermore, please subscribe to my email newsletter for updates on the newest articles.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top