If you happen to be using a data.table
(and why would anyone not use it, if you are using a data.frame anyway?) - then you can use the handy .N
operator (more info), which in essence contains the number of rows in your table.
Here's a working example:
# make sure you have data.table
install.packages("data.table")
library(data.table)
# load the mtcars data
data(mtcars)
# Make a data table out of the mtcars dataset
cars <- as.data.table(mtcars, keep.rownames = TRUE)
# Take all the rows from a given index (e.g. 5) to the end
> cars[5:.N]
rn mpg cyl disp hp drat wt qsec vs am gear carb
1: Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
2: Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
3: Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
4: Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
... (truncated)
Just swap that 5 for a 2 in order to get the OP's desired output.
This of course allows dynamic use for tables of varying lengths, without having to always use the length()
function. For example, if you know that you always want take the last 5 rows of a table and remove the very last row - getting 4 rows as output - then you can do something like the following:
> cars[(.N-4):(.N-1)] # note the expressions for slicing must be in parentheses
rn mpg cyl disp hp drat wt qsec vs am gear carb
1: Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.9 1 1 5 2
2: Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.5 0 1 5 4
3: Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.5 0 1 5 6
4: Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.6 0 1 5 8
Or simply always get the last row:
cars[.N]
... which is just as nice and concise as Python's equivalent: cars[-1]