tail

Basics

tail functionally mirrors head — it returns the last n values of an object, with default n = 6. You can put a negative sign in front of the n argument to exclude the first n values.


Examples

How do I get the last 6 rows of data.frame iris?

Click to see solution
tail(iris)
    Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
145          6.7         3.3          5.7         2.5 virginica
146          6.7         3.0          5.2         2.3 virginica
147          6.3         2.5          5.0         1.9 virginica
148          6.5         3.0          5.2         2.0 virginica
149          6.2         3.4          5.4         2.3 virginica
150          5.9         3.0          5.1         1.8 virginica

How do I get the last 10 rows of iris?

Click to see solution
tail(iris, 10)
    Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
141          6.7         3.1          5.6         2.4 virginica
142          6.9         3.1          5.1         2.3 virginica
143          5.8         2.7          5.1         1.9 virginica
144          6.8         3.2          5.9         2.3 virginica
145          6.7         3.3          5.7         2.5 virginica
146          6.7         3.0          5.2         2.3 virginica
147          6.3         2.5          5.0         1.9 virginica
148          6.5         3.0          5.2         2.0 virginica
149          6.2         3.4          5.4         2.3 virginica
150          5.9         3.0          5.1         1.8 virginica

Return only measurements from the 1900s in dataset LakeHuron.

Click to see solution

Let’s look at the structure of LakeHuron using the str function.

str(LakeHuron)
Time-Series [1:98] from 1875 to 1972: 580 582 581 581 580 ...

We see from this output that there are 98 measurements, starting in 1875 and ending in 1972. To return the 1900s measurements, we can remove the first 25 measurements (from 1875 to 1899)

tail(LakeHuron, n=-25)
 [1] 578.82 579.32 579.01 579.00 579.80 579.83 579.72 579.89 580.01 579.37 578.69 578.19
[13] 578.67 579.55 578.92 578.09 579.37 580.13 580.14 579.51 579.24 578.66 578.86 578.05
[25] 577.79 576.75 576.75 577.82 578.64 580.58 579.48 577.38 576.90 576.94 576.24 576.84
[37] 576.85 576.90 577.79 578.18 577.51 577.23 578.42 579.61 579.05 579.26 579.22 579.38
[49] 579.10 577.95 578.12 579.75 580.85 580.41 579.96 579.61 578.76 578.18 577.21 577.13
[61] 579.10 578.25 577.91 576.89 575.96 576.80 577.68 578.38 578.52 579.74 579.31 579.89
[73] 579.96