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?
To remove the multiple rows in R, use the subsetting and pass the vector with multiple elements. The elements are the row index, which we need to remove. To remove the second and third-row in R, use -c(2, 3), and it will return the data frame without the second and third row.
By using bracket notation on R DataFrame (data.name) we can select rows by column value, by index, by name, by condition e.t.c. You can also use the R base function subset() to get the same results. Besides these, R also provides another function dplyr::filter() to get the rows from the DataFrame.
R – Get Multiple Rows of Matrix To get multiple rows of matrix, specify the row numbers as a vector followed by a comma, in square brackets, after the matrix variable name. This expression returns the required rows as a matrix.
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),]
I prefer using tail
with negative values for n
:
tail(mtcars,-2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With