Remove Bottom N Rows from Data Frame in R (2 Examples)
In this tutorial, I’ll explain how to drop the last N rows of a data frame in the R programming language.
Table of contents:
Let’s dig in.
Creation of Exemplifying Data
First and foremost, let’s create some example data:
data <- data.frame(x1 = LETTERS[1:10], # Create example data frame x2 = 1:10, x3 = 20:11) data # Print example data frame
As you can see based on Table 1, our exemplifying data is a data frame containing ten rows and three columns.
Example 1: Delete Bottom N Rows of Data Frame Using head() Function
In this section, I’ll illustrate how to use the head function to remove the bottom 3 rows of our data frame.
Within the head function, we simply have to specify the number of rows that we want to delete with a minus sign in front.
Consider the R cod below:
data_new1 <- head(data, - 3) # Apply head function data_new1 # Print data without bottom rows
After running the previous R programming code the data frame shown in Table 2 has been created. As you can see, our output data frame has only seven rows, i.e. three rows have been removed.
Example 2: Delete Bottom N Rows of Data Frame Using slice() & n() Functions of dplyr Package
Example 2 explains how to remove the last N rows of a data frame using the dplyr package.
To be able to use the functions of the dplyr package, we first need to install and load dplyr:
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package
Now, we can apply the slice and n function to delete the last N rows of our data frame.
Similar to the previous example, we have to specify the number of rows that we want to delete with a minus sign in front:
data_new2 <- slice(data, 1:(n() - 3)) # Apply slice & n functions data_new2 # Print data without bottom rows
By running the previous R programming syntax we have created Table 3, i.e. a data frame without the last three lines.
Video, Further Resources & Summary
Do you want to know more about data manipulation and data frames in R? Then I can recommend watching the following video of my YouTube channel. In the video, I show the contents of this article in R:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you might read some of the other tutorials of my homepage.
- Repeat Rows of Data Frame N Times
- Extract First N Rows of Data Frame
- Remove Rows with NA in R
- Create Data Frame with n Rows & m Columns
- Conditionally Remove Row from Data Frame in R
- Remove Empty Rows of Data Frame
- All R Programming Examples
This tutorial has shown how to get rid of the bottom N rows of a data frame in R. If you have any additional questions, let me know in the comments.
Statistics Globe Newsletter