Get the Last n Rows of a Data Frame in R

Your goal

You need to get the last n rows of a data frame in R.

Step-by-step tutorial

You can use the tail function from the utils package to do this for a standard data frame or else for a tibble. It works the same way for each.

Data frame

By default, tail returns the last six rows:

> precip <- read.csv("precip-central-park.csv")
> tail(precip)
    YEAR  JAN  FEB  MAR  APR  MAY  JUN  JUL  AUG  SEP  OCT  NOV  DEC ANNUAL
146 2014 2.79 5.48 3.67 7.85 4.37 4.26 5.59 2.25 1.21 5.77 4.51 6.04  53.79
147 2015 5.23 2.04 4.72 2.08 1.86 4.79 3.98 2.35 3.28 3.91 2.01 4.72  40.97
148 2016 4.41 4.40 1.17 1.61 3.75 2.60 7.02 1.97 2.79 4.15 5.41 2.89  42.17
149 2017 4.83 2.48 5.25 3.84 6.38 4.76 4.19 3.34 2.00 4.18 1.58 2.21  45.04
150 2018 2.18 5.83 5.17 5.78 3.53 3.11 7.45 8.59 6.19 3.59 7.62 6.51  65.55
151 2019 3.58 3.14 3.87 4.55 6.82 5.46 5.77 3.70 0.95 6.15 1.95 7.09  53.03

You can change the number of rows as follows:

> tail(precip, 3)
    YEAR  JAN  FEB  MAR  APR  MAY  JUN  JUL  AUG  SEP  OCT  NOV  DEC ANNUAL
149 2017 4.83 2.48 5.25 3.84 6.38 4.76 4.19 3.34 2.00 4.18 1.58 2.21  45.04
150 2018 2.18 5.83 5.17 5.78 3.53 3.11 7.45 8.59 6.19 3.59 7.62 6.51  65.55
151 2019 3.58 3.14 3.87 4.55 6.82 5.46 5.77 3.70 0.95 6.15 1.95 7.09  53.03

Tibble

It's the same for a tibble

> library(readr)
> precip <- read_csv("precip-central-park.csv")
Parsed with column specification:
cols(
  YEAR = col_double(),
  JAN = col_double(),
  FEB = col_double(),
  MAR = col_double(),
  APR = col_double(),
  MAY = col_double(),
  JUN = col_double(),
  JUL = col_double(),
  AUG = col_double(),
  SEP = col_double(),
  OCT = col_double(),
  NOV = col_double(),
  DEC = col_double(),
  ANNUAL = col_double()
)
> tail(precip)
# A tibble: 6 x 14
   YEAR   JAN   FEB   MAR   APR   MAY   JUN   JUL   AUG   SEP   OCT   NOV   DEC
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1  2014  2.79  5.48  3.67  7.85  4.37  4.26  5.59  2.25  1.21  5.77  4.51  6.04
2  2015  5.23  2.04  4.72  2.08  1.86  4.79  3.98  2.35  3.28  3.91  2.01  4.72
3  2016  4.41  4.4   1.17  1.61  3.75  2.6   7.02  1.97  2.79  4.15  5.41  2.89
4  2017  4.83  2.48  5.25  3.84  6.38  4.76  4.19  3.34  2     4.18  1.58  2.21
5  2018  2.18  5.83  5.17  5.78  3.53  3.11  7.45  8.59  6.19  3.59  7.62  6.51
6  2019  3.58  3.14  3.87  4.55  6.82  5.46  5.77  3.7   0.95  6.15  1.95  7.09
# … with 1 more variable: ANNUAL <dbl>
> tail(precip, 3)
# A tibble: 3 x 14
   YEAR   JAN   FEB   MAR   APR   MAY   JUN   JUL   AUG   SEP   OCT   NOV   DEC
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1  2017  4.83  2.48  5.25  3.84  6.38  4.76  4.19  3.34  2     4.18  1.58  2.21
2  2018  2.18  5.83  5.17  5.78  3.53  3.11  7.45  8.59  6.19  3.59  7.62  6.51
3  2019  3.58  3.14  3.87  4.55  6.82  5.46  5.77  3.7   0.95  6.15  1.95  7.09
# … with 1 more variable: ANNUAL <dbl>