A dataframe in R is a data structure used to store data in a tabular form – in rows and columns. In this tutorial, we will look at how to get the last n rows of an R dataframe with the help of some examples.
How to extract the last n rows in R?
You can use the
tail() function in R to extract the last n rows of a dataframe. Pass the dataframe and n (the number of rows you want from the end) as arguments to the
The following is the syntax –
# get last n rows tail(dataframe, n)
If you do not pass a value for
tail() function returns the last 6 rows of the dataframe by default.
Steps to get the last n rows of a dataframe in R
Let’s now look at a step-by-step example to show the usage of the syntax mentioned above.
Step 1 – Create a dataframe
First, we will create a dataframe that we will be using throughout this tutorial.
# create a dataframe employees_df = data.frame( "Name"= c("Jim", "Dwight", "Angela", "Tobi", "Kevin", "Meredith", "Creed"), "Age"= c(26, 28, 29, 32, 30, 38, 49), "Department"= c("Sales", "Sales", "Accounting", "HR", "Accounting", "QA", "QA") ) # display the dataframe print(employees_df)
Name Age Department 1 Jim 26 Sales 2 Dwight 28 Sales 3 Angela 29 Accounting 4 Tobi 32 HR 5 Kevin 30 Accounting 6 Meredith 38 QA 7 Creed 49 QA
We now have a dataframe containing some information about employees in an office. The dataframe has the columns – “Name”, “Age”, and “Department”. Note that the dataframe above has 7 rows.
Step 2 – Extract the last n rows of dataframe using
First, let’s use the
tail() function without specifying a value for n and see what we get.
# tail() with default n print(tail(employees_df))
Name Age Department 2 Dwight 28 Sales 3 Angela 29 Accounting 4 Tobi 32 HR 5 Kevin 30 Accounting 6 Meredith 38 QA 7 Creed 49 QA
We get the last six rows (row 2 to row 7) of the dataframe by default from the
Let’s now pass a custom value for n.
For example, let’s just get the last two rows of the above dataframe.
# last two rows print(tail(employees_df, 2))
Name Age Department 6 Meredith 38 QA 7 Creed 49 QA
Here, we specify n as 2 and thus we get the last two rows of the dataframe.
Summary – Extract last n rows in R
In this tutorial, we looked at how to get the last n rows of a dataframe in R. The following is a short summary of the steps mentioned in this tutorial.
- Create a dataframe (skip this step if you already have a dataframe to operate on).
- Use the
tail()function to get the last n rows of the dataframe. Pass the number of rows you want from the end as an argument. If you do not specify n, the
tail()function returns the last six rows by default.
You might also be interested in –
- How to Create a DataFrame in R?
- How to Add a Row to a Dataframe in R?
- Rename Column Name in R Dataframe
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.