dplyr slice() in R: A Complete Guide to Selecting Rows
Learn dplyr slice() in R with beginner-friendly examples. This guide explains how to select rows by row number, take the first or last records, find the smallest and largest values, sample rows randomly, and use slice functions with grouped data.
What is slice() in R?
slice() is a function from the dplyr package that selects rows according to their position in a data frame or tibble. If you want rows 1, 2, and 3, you can request those row positions directly rather than writing a condition about the values in the data.
The main idea is simple: slice() answers “which row numbers do I want?” Other dplyr functions answer different questions. For example, filter() keeps rows that satisfy a condition, arrange() sorts rows, and select() chooses columns.
library(dplyr)
# Select rows 1, 2, and 3
slice(sales, 1:3)
Important: row positions refer to the current order of the data. If you sort the data first, row 1 may refer to a different observation. If you want the highest or lowest values, slice_max() or slice_min() is usually clearer than manually sorting and selecting row numbers.
Create example data for slice() in R
Throughout this tutorial, we will use a small sales dataset. Each row represents one sale, and the columns contain the sale ID, salesperson, region, product, and sales amount.
library(dplyr)
sales <- tibble(
sale_id = 1:7,
salesperson = c("Amina", "Bilal", "Sara", "Omar", "Hina", "Usman", "Noor"),
region = c("North", "South", "North", "West", "South", "North", "West"),
product = c("Laptop", "Keyboard", "Monitor", "Laptop", "Mouse", "Tablet", "Monitor"),
amount = c(1250, 80, 320, 1100, 35, 480, 290)
)
sales
| sale_id | salesperson | region | product | amount |
|---|---|---|---|---|
We can now use the same data to select specific positions, find high-value sales, compare regions, and create samples for analysis.
1. Select rows by position with slice()
The basic syntax is slice(.data, ...). The first argument is the dataset, and the remaining arguments identify row positions. A colon creates a sequence of integers in R.
Select one row
slice(sales, 1)
This returns the first row in the current order of sales.
Select a range of rows
# Rows 2 through 5
slice(sales, 2:5)
This is useful when inspecting a small section of a large dataset, checking imported records, or reviewing rows after a transformation.
Select specific, non-consecutive rows
# Rows 1, 3, and 6
slice(sales, c(1, 3, 6))
Use a vector of row numbers when the positions you need are not next to one another. You can also save the selected rows in a new object:
selected_sales <- slice(sales, c(1, 3, 6))
What if a requested position is outside the data?
Positions beyond the number of rows are ignored rather than creating additional rows. For example, if a dataset has seven rows, asking for row 10 does not produce a new tenth row.
# The dataset has only seven rows
slice(sales, 5:10)
This returns the existing rows among positions 5 through 10. Be careful when row positions are calculated dynamically, because an unexpectedly small dataset may contain fewer rows than you expect.
2. Select the first and last rows with slice_head() and slice_tail()
For common tasks such as returning the first few or last few records, dplyr provides dedicated helpers. These communicate your intention more clearly than a hard-coded row sequence.
slice_head(): return the first rows
# First three rows
slice_head(sales, n = 3)
The n argument specifies how many rows to keep. This is handy for checking a dataset after importing a CSV file, viewing a sample of records, or quickly checking the output of a data-cleaning pipeline.
slice_tail(): return the last rows
# Last two rows
slice_tail(sales, n = 2)
Use this when you want to inspect the end of a dataset. For time-series data, remember that the last rows are only the most recent observations if the data is already sorted by date in ascending order.
Select a proportion instead of a fixed count
The prop argument selects a proportion of rows. It can be useful when dataset sizes vary between runs.
# First 25 percent of rows
slice_head(sales, prop = 0.25)
# Last 20 percent of rows
slice_tail(sales, prop = 0.20)
Use either n or prop for a given call. A proportion is interpreted relative to the number of rows, and the resulting count is rounded down.
3. Select the smallest and largest values with slice_min() and slice_max()
Often, the goal is not to select a row because of its position in the original data. Instead, you may want the five largest sales, the three lowest exam scores, or the products with the longest delivery times. Use slice_min() and slice_max() for these tasks.
slice_max(): find the highest values
# Three sales with the largest amounts
slice_max(sales, order_by = amount, n = 3)
The order_by argument identifies the variable used to rank rows. By default, slice_max() returns the rows with the largest values.
slice_min(): find the lowest values
# Two sales with the smallest amounts
slice_min(sales, order_by = amount, n = 2)
This could identify the lowest-value transactions for review, the cheapest items in a catalogue, or the shortest processing times in an operations dataset.
Return the top 10 percent
# Rows with the largest 10 percent of amounts
slice_max(sales, order_by = amount, prop = 0.10)
Proportions can be useful when the number of records changes over time. For example, an analyst might inspect the highest 5% of customer balances each month rather than always selecting exactly 20 customers.
Sort the results for easier reading
slice_max() identifies rows based on the requested values, but the result should not be treated as a promise of a particular display order in every workflow. If you want the selected rows explicitly sorted from largest to smallest, combine it with arrange().
sales |>
slice_max(order_by = amount, n = 3) |>
arrange(desc(amount))
This is an example of a dplyr pipeline. The native R pipe |> passes the result of one step to the next. Read more about the pipe operator in R.
4. Understand ties and missing values
When several rows have the same value at the cutoff, you need to decide whether to keep every tied row or return exactly the number requested.
Keep all tied values
By default, slice_max() and slice_min() use with_ties = TRUE. If the third-highest value is shared by two rows, a request for three rows can return four rows so that both tied observations are included.
scores <- tibble(
student = c("Ali", "Bea", "Chen", "Dia"),
score = c(98, 92, 92, 85)
)
# May return both students tied at the cutoff
slice_max(scores, order_by = score, n = 2)
Return exactly the requested number of rows
Set with_ties = FALSE when you need no more than the specified number of rows.
# Return exactly two rows when at least two rows are available
slice_max(scores, order_by = score, n = 2, with_ties = FALSE)
If tied rows have no unique ranking rule, which tied row is retained can depend on their order. When reproducibility matters, define a meaningful tie-breaker, such as sorting by score and then by student name, or create an explicit ranking rule.
Control missing values with na_rm
When the ranking variable contains missing values, na_rm = TRUE removes missing values before selecting the requested smallest or largest values. If there are not enough non-missing observations, fewer than n rows may be returned.
scores_with_na <- tibble(
student = c("Ali", "Bea", "Chen", "Dia"),
score = c(98, 92, NA, 85)
)
slice_max(
scores_with_na,
order_by = score,
n = 2,
na_rm = TRUE
)
Data-quality tip: Do not automatically remove missing values without understanding them. A missing sales amount may indicate an incomplete transaction, a data-entry problem, or a legitimate unavailable value. Decide how to handle missingness based on the analysis.
5. Use slice functions with group_by()
One of the most useful features of dplyr is that slice helpers work within groups. Grouping changes the question from “Which are the three largest sales overall?” to “Which are the three largest sales in each region?”
Top two sales in each region
sales |>
group_by(region) |>
slice_max(order_by = amount, n = 2)
This returns up to two high-value rows for every region. A region with fewer than two observations will return fewer rows. Ties may also increase the number returned unless you use with_ties = FALSE.
Lowest sale in each region
sales |>
group_by(region) |>
slice_min(order_by = amount, n = 1)
This helps compare the minimum transaction in each region. It can also be adapted to the lowest exam score by class, shortest delivery time by warehouse, or lowest monthly revenue by product category.
First and last record in every group
# First row in each region, based on current row order
sales |>
group_by(region) |>
slice_head(n = 1)
# Last row in each region, based on current row order
sales |>
group_by(region) |>
slice_tail(n = 1)
These examples use the current row order inside each group. If “first” means the earliest date or “last” means the latest date, arrange by the date first.
transactions |>
group_by(customer_id) |>
arrange(transaction_date, .by_group = TRUE) |>
slice_head(n = 1)
This returns the earliest dated transaction per customer, assuming transaction_date is correctly stored as a date or date-time variable.
Remove grouping when you no longer need it
A grouped data frame remains grouped for later operations unless you ungroup it or use a helper that changes the grouping. You can use ungroup() when subsequent steps should apply to the full dataset.
top_by_region <- sales |>
group_by(region) |>
slice_max(order_by = amount, n = 2) |>
ungroup()
For a related explanation of group-level calculations, see group_by() and summarise() in R.
6. Randomly sample rows with slice_sample()
slice_sample() selects rows randomly. Sampling can help you inspect a large dataset, create a quick review subset, or select records for exploratory analysis. It can sample a fixed number of rows or a proportion of the data.
Randomly select five rows
slice_sample(sales, n = 5)
Randomly select 30 percent of the rows
slice_sample(sales, prop = 0.30)
Make the sample reproducible
Random sampling can return different rows on different runs. Use set.seed() before sampling when you need to reproduce the same result in a script, classroom exercise, or analysis report.
set.seed(123)
sample_one <- slice_sample(sales, n = 3)
set.seed(123)
sample_two <- slice_sample(sales, n = 3)
With the same data and R random-number setup, resetting the seed before each call makes the sampling repeatable.
Sample with replacement
By default, sampling is without replacement, so a row is not selected more than once. If your method requires sampling with replacement, set replace = TRUE.
set.seed(123)
slice_sample(sales, n = 10, replace = TRUE)
Sampling more rows than exist is possible with replacement, but not with ordinary sampling without replacement. Use replacement only when it matches the design of your analysis.
Take a sample from each group
set.seed(123)
sales |>
group_by(region) |>
slice_sample(n = 1)
Grouped sampling can help create a small sample from each region. If some groups contain fewer rows than the requested sample size, the call may fail unless replacement is used or the sample size is adjusted.
7. Exclude row positions with negative indices
Like many base R indexing operations, slice() can use negative positions to omit rows. This is useful when you want all rows except one or more positions.
# All rows except the first
slice(sales, -1)
# All rows except the second and fourth
slice(sales, c(-2, -4))
Do not mix positive and negative indices in the same selection. For clearer code, especially for beginners, selecting the rows to keep is often easier to read than listing the positions to exclude.
8. Combine slice() with other dplyr functions
In real analysis, row selection is often one step in a larger workflow. You can combine slice() helpers with filtering, sorting, grouping, and summarising to answer more specific questions.
Filter first, then select the top rows
# Find the three highest-value laptop sales
sales |>
filter(product == "Laptop") |>
slice_max(order_by = amount, n = 3)
Here, filter() narrows the data to laptop sales and slice_max() selects the highest amounts from those rows.
Arrange first, then take the first rows
# Five largest amounts, explicitly sorted descending
sales |>
arrange(desc(amount)) |>
slice_head(n = 5)
This pattern is valid, although slice_max(order_by = amount, n = 5) usually states the intention more directly.
Choose the top row per category
# Highest-value sale for each product
sales |>
group_by(product) |>
slice_max(order_by = amount, n = 1, with_ties = FALSE) |>
ungroup()
When each product appears in several records, this returns one row per product. If multiple sales tie for the maximum and you keep the default with_ties = TRUE, more than one row per product may be returned.
Keep the output focused with select()
sales |>
group_by(region) |>
slice_max(order_by = amount, n = 2) |>
ungroup() |>
select(region, salesperson, amount)
Use select() at the end to show only the columns needed for a report. For a deeper explanation, read the dplyr select() tutorial.
9. Practical applications of slice() in data analytics
Business and sales analytics
Business analysts often need to identify the highest-value transactions, inspect the smallest orders, or report the best-performing items in each region. slice_max() and grouped slice functions are suitable for these tasks.
# Top five orders by revenue
orders |>
slice_max(order_by = revenue, n = 5) |>
arrange(desc(revenue))
Finance and investment analysis
Financial datasets may contain daily returns, stock prices, or portfolio records. Once the data is ordered by date, slice_tail() can help inspect the latest observations. To select the largest or smallest returns, use the value-based helpers instead.
# Assuming prices are sorted by date, inspect the last ten records
prices |>
arrange(date) |>
slice_tail(n = 10)
For market analysis, make sure the data is sorted by the correct date field and that any ranking reflects the question being asked. The largest return is not necessarily the latest return.
Education and student performance
Teachers and education researchers may need to review the highest scores, lowest scores, or top students in each class.
# Top three students in each class
student_scores |>
group_by(class) |>
slice_max(order_by = score, n = 3) |>
ungroup()
Operations and service quality
Operations teams can use row selection to investigate the longest delivery times or the most expensive service cases.
# Ten longest delivery times
shipments |>
slice_max(order_by = delivery_days, n = 10) |>
arrange(desc(delivery_days))
Exploratory data analysis and quality checks
Random samples and small row previews help analysts inspect values before building charts or models. For formal machine-learning evaluation, however, do not rely on an unplanned random sample as a substitute for a proper train/test split or a sampling design that reflects the research question.
# Reproducible random sample for inspection
set.seed(42)
inspection_sample <- slice_sample(raw_data, n = 20)
10. slice() vs filter() and base R row indexing
These tools can all select rows, but they use different ways to express the selection.
| Goal | dplyr approach | What it means |
|---|---|---|
| Select rows 1 to 5 | slice(data, 1:5) | Choose by row position |
| Select first five rows | slice_head(data, n = 5) | Choose the start of the current row order |
| Keep values above 100 | filter(data, value > 100) | Choose by a logical condition |
| Choose largest five values | slice_max(data, order_by = value, n = 5) | Choose by value ranking |
| Base R rows 1 to 5 | data[1:5, ] | Base R row indexing |
For example, these two expressions select the first five rows:
slice(sales, 1:5)
sales[1:5, ]
Use whichever style fits the codebase, but be consistent. In a dplyr pipeline, slice() and its helpers make the intention explicit and integrate naturally with functions such as filter(), arrange(), and group_by().
11. Common slice() errors and how to fix them
Error 1: Using slice() to filter by a value
Problem: Trying to write slice(sales, amount > 100).
Why it happens: slice() expects row positions, not a logical condition on a column.
Fix: Use filter(sales, amount > 100) to keep sales whose amount exceeds 100.
Error 2: Expecting the largest values from slice_head()
Problem: Calling slice_head(sales, n = 3) and expecting the three highest sales.
Why it happens: slice_head() returns the first rows in the current order. It does not rank values.
Fix: Use slice_max(sales, order_by = amount, n = 3), or sort with arrange(desc(amount)) before using slice_head().
Error 3: Getting more rows than requested
Problem: Asking for three top values but receiving four or more rows.
Why it happens: Tied values at the cutoff are included by default.
Fix: Set with_ties = FALSE if you require no more than the specified number of rows. Consider defining a tie-breaker if the selected record must be deterministic.
Error 4: Selecting the wrong “latest” records
Problem: Using slice_tail() and assuming it returns the latest dates.
Why it happens: It selects the last rows in the current order, which may not be chronological.
Fix: Sort by date first, for example arrange(data, date), then use slice_tail().
Error 5: A grouped slice returns several rows per group
Problem: Expecting one row per region but getting multiple rows.
Why it happens: There may be tied values, or the requested n may be greater than one.
Fix: Use n = 1 and, if appropriate, with_ties = FALSE. If the result must always choose a specific record, add a clear secondary ordering rule.
Error 6: Random samples change between runs
Problem: slice_sample() returns different records when the code runs again.
Why it happens: Sampling is random by design.
Fix: Use set.seed() before sampling when repeatability is important, and keep the data and code consistent.
12. Practice exercises: dplyr slice() in R
Try each task before expanding the answer. The examples use the sales data frame created earlier in this tutorial.
Exercise 1: Select rows 2 through 4
Return rows at positions 2, 3, and 4 from the current data order.
Show answer
slice(sales, 2:4)Exercise 2: Return the last two rows
Use a helper function to return the final two records.
Show answer
slice_tail(sales, n = 2)Exercise 3: Find the three largest sales
Return the rows with the three highest amount values.
Show answer
slice_max(sales, order_by = amount, n = 3)Exercise 4: Find the highest sale in each region
Use group_by() and slice_max() to select the top sale per region. Return no more than one row per region.
Show answer
sales |>
group_by(region) |>
slice_max(order_by = amount, n = 1, with_ties = FALSE) |>
ungroup()Exercise 5: Take a repeatable random sample
Set a seed and select three rows randomly.
Show answer
set.seed(123)
slice_sample(sales, n = 3)dplyr FAQ
What does slice() do in dplyr?
slice() selects rows by their integer positions in a data frame or tibble. For example, slice(data, 1:5) returns rows 1 through 5.
How do I select the first five rows in R using dplyr?
Use slice_head(data, n = 5) to select the first five rows. You can also use slice(data, 1:5) when you specifically want rows at positions 1 through 5.
What is the difference between slice() and filter()?
slice() selects rows by position, while filter() selects rows based on logical conditions such as sales > 1000. Use slice() for row numbers and filter() for values or rules.
How do I select the top five values in R?
Use slice_max(data, order_by = value, n = 5). If you need exactly five rows when there are ties, set with_ties = FALSE.
How do I select the lowest values with dplyr?
Use slice_min(data, order_by = value, n = 5) to return rows with the five smallest values in that column.
How do I get the last rows in R?
Use slice_tail(data, n = 5) to return the last five rows.
How can I randomly select rows in R?
Use slice_sample(data, n = 10) to sample ten rows, or slice_sample(data, prop = 0.2) to sample approximately 20 percent of the rows. Set a seed with set.seed() for reproducibility.
Does slice() work with grouped data?
Yes. When data is grouped with group_by(), slice functions operate within each group. For example, slice_max(data, order_by = sales, n = 3) can return the three highest-sales rows in each group.
Key points to remember
slice()selects rows by their current integer positions.slice_head()andslice_tail()return the first or last rows in the current order.slice_min()andslice_max()select rows with the smallest or largest values in a variable.- Use
with_ties = FALSEwhen you need no more than the requested number of rows; define a tie-breaker when necessary. - Use
group_by()with slice helpers to select rows within each group. slice_sample()randomly samples rows; useset.seed()for reproducibility.- Use
filter()for conditions andarrange()to make row order explicit.
Next, learn about window functions in dplyr. You can also review filter(), arrange(), group_by() and summarise(), or return to the dplyr tutorial overview.