R syntax for selecting all but two first rows

Christian Madsen picture Christian Madsen · Apr 3, 2012 · Viewed 44.1k times · Source

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?

Answer

TMS picture TMS · Apr 3, 2012

Negative indices mean "skip":

mtcars[-(1:2)]

skips first 2 indices of vector mtcars. If you need to skip first 10, just use mtcars[-(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. If mtcars is a dataframe and you are selecting rows, you have to use trailing comma:

mtcars[-(1:2),]