Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R syntax for selecting all but two first rows

Tags:

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?

like image 798
Christian Madsen Avatar asked Apr 03 '12 17:04

Christian Madsen


People also ask

How do I remove the first 3 rows in R?

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.

How do I select rest of rows in R?

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.

How do I select two rows in a matrix in R?

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.


2 Answers

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),] 
like image 103
Tomas Avatar answered Sep 27 '22 02:09

Tomas


I prefer using tail with negative values for n:

tail(mtcars,-2) 
like image 30
Joshua Ulrich Avatar answered Sep 26 '22 02:09

Joshua Ulrich