slice( )
Keep rows by their position. slice() is from the dplyr package, which is part of the tidyverse.
Required Library
install.packages("tidyverse")
library(tidyverse)Syntax
# Pipe style
df %>% slice(row_numbers)
# Non-pipe style
slice(df, row_numbers)df %>% slice(2:4) and slice(df, 2:4) keep rows by their position in the data, not by a condition on the values. Negative positions drop rows instead of keeping them.
df %>% slice_max(column, n = 1)
df %>% slice_min(column, n = 1)slice_max() and slice_min() keep the row(s) with the highest or lowest value of a column. They are a shortcut for arrange() followed by slice(), and handle ties explicitly.
slice()?
Use slice() when you want rows by position — for example the first three rows, every other row, or “the row with the highest value” per group. Use filter() instead when you want rows that match a logical condition on their values.
Examples
Keep rows by position
Drop rows by position
A negative position removes that row instead of keeping it.
Keep the row with the highest value using slice_max()
Keep the first row of each group
slice() respects group_by(), so it can pick rows within each group instead of across the whole table.
Extract a single value with pull()
slice() always returns a data frame, even for one row. Chain in pull() when you want the bare value instead of a one-row table.
Argument Overview
Required arguments must be included when using a function while optional arguments can be included on demand.
.data data frame | tibble Required
The data frame to slice. In a pipe (%>%), this is passed automatically from the left-hand side.
tablet_weights %>% slice(1:3)
Data Types: data.frame | tibble
… — row positions to keep integer(s) | range Required
One or more row positions, given as numbers or a range such as 2:4. Use negative numbers to drop rows instead of keeping them. Positions can’t be mixed positive and negative in the same call.
tablet_weights %>% slice(c(1, 3, 5))
tablet_weights %>% slice(-c(1, 2))
Data Types: integer vector or range
.by — group rows before slicing column name(s) Optional
Slice within each group instead of across the whole table, without needing a separate group_by() call.
tablet_weights %>% slice(1, .by = batch)
Data Types: column name(s) · Default: NULL
order_by / n — used by slice_max() and slice_min() column | integer Optional
slice_max() and slice_min() take a column to rank by and an n for how many rows to keep. Ties are kept by default, so more than n rows can be returned.
tablet_weights %>% slice_max(weight_mg, n = 1)
tablet_weights %>% slice_min(weight_mg, n = 3)
Data Types: order_by: column name · n: integer, default 1