How do I select all but the first two rows from e.g. the mtcars dataset?
I know that I can write no_mazda <- mtcars[3:32]
, which does work as long as I know the number of rows. But when I don't know the number of rows I need to write e.g. no_mazda <- mtcars[3:nrow(mtcars)]
which of cause also works, but:
Does R provide a smarter syntax than an expression that includes mtcars
twice?
I prefer using
tail
with negative values forn
:Negative indices mean "skip":
skips first 2 indices of vector
mtcars
. If you need to skip first 10, just usemtcars[-(1:10)]
.Note that you speak about "dataset" but the code you use is for vectors, so I also responded is if
mtcars
is a vector. Ifmtcars
is a dataframe and you are selecting rows, you have to use trailing comma: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:
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:Or simply always get the last row:
... which is just as nice and concise as Python's equivalent:
cars[-1]
)