slice {dplyr} | R Documentation |
Slice does not work with relational databases because they have no
intrinsic notion of row order. If you want to perform the equivalent
operation, use filter()
and row_number()
.
slice(.data, ...)
.data |
A tbl. |
... |
Integer row values. These arguments are automatically quoted and
evaluated in the context of the data
frame. They support unquoting and
splicing. See |
Positive values select rows to keep; negative values drop rows. The values provided must be either all positive or all negative.
When applied to a data frame, row names are silently dropped. To preserve,
convert to an explicit variable with tibble::rownames_to_column()
.
Other single table verbs: arrange
,
filter
, mutate
,
select
, summarise
slice(mtcars, 1L) slice(mtcars, n()) slice(mtcars, 5:n()) # Rows can be dropped with negative indices: slice(mtcars, -5:-n()) # In this case, the result will be equivalent to: slice(mtcars, 1:4) by_cyl <- group_by(mtcars, cyl) slice(by_cyl, 1:2) # Equivalent code using filter that will also work with databases, # but won't be as fast for in-memory data. For many databases, you'll # need to supply an explicit variable to use to compute the row number. filter(mtcars, row_number() == 1L) filter(mtcars, row_number() == n()) filter(mtcars, between(row_number(), 5, n()))