# What is the tail() Function in R

The tail() is a built-in R function “used to display the last n rows in the input data frame”.

### Syntax

``tail(x, n)``

### Parameters

x: It is an input dataset / dataframe.

n:  It is the number of rows that the function should display.

### Return value

The tail() function returns the last n rows of the dataset.

## Example 1: The tail() function with data frame

Let’s get the last three rows of the data frame using the tail() function.

``````df <- data.frame(c1 = c("a", "b", "c", "d"),
c2 = c("e", "f", "g", "h"),
c3 = c("i", "j", "k", "l"),
c4 = c("m", "n", "o", "p"),
c5 = c("q", "r", "s", "t"))
df
cat("Last two rows of data frame", "\n")
tail(df, 2)
``````

Output

``````   c1 c2 c3 c4 c5
1  a  e  i  m  q
2  b  f  j  n  r
3  c  g  k  o  s
4  d  h  l  p  t
Last two rows of data frame
c1 c2 c3 c4 c5
3  c  g  k  o  s
4  d  h  l  p  t
``````

While using the tail() function, we passed 2: a positive integer as an argument, which indicates the last 2 parts or, in our case, the first two rows of the data frame.

## Example 2: The tail() function with Vector

Applying the tail() function on a Vector will return the number of elements equal to the n parameter of the tail() function.

``````rv <- 1:10
rv
cat("Last five integers of vector", "\n")
tail(rv, 5)``````

Output

``````[1] 1 2 3 4 5 6 7 8 9 10
Last five integers of vector
[1] 6 7 8 9 10``````

In this example, the n parameter of the tail() function is 5, which means it will return the last five elements of the vector, which it did in the output.

## Example 3: The tail() function with Matrix

Fetch the last 2 rows of the Matrix using the tail() function.

``````rv <- 1:15
mtrx <- matrix(rv, nrow = 5, ncol = 3)
mtrx
cat("Using tail() function to get the last 2 rows", "\n")
tail(mtrx, 2)``````

Output

``````     [,1] [,2] [,3]
[1,]  1    6    11
[2,]  2    7    12
[3,]  3    8    13
[4,]  4    9    14
[5,]  5   10    15
Using tail() function to get the last 2 rows
[,1] [,2] [,3]
[4,]  4    9   14
[5,]  5   10   15``````

In this example, we used the tail() function and passed the Matrix and a number of rows as arguments, and it returns the Matrix with the last two rows.

## Example 4: The tail() function with a built-in dataset

We will import the ChickWeight inbuilt R dataset and use the tail() function on that dataset.

``df <- datasets::ChickWeight``

Use the tail() function to get the last five rows of the dataset.

``````df <- datasets::ChickWeight
tail(df, 5)``````

Output

``````     weight Time Chick Diet
574   175   14    50    4
575   205   16    50    4
576   234   18    50    4
577   264   20    50    4
578   264   21    50    4``````

As you can see that we only get the last five rows of the dataset.

That is it.