slice() Function in R
Definition of slice()
1. slice() function in R is a dplyr package function that allows us to select rows from a
data frame (or tibble) based on their row positions.
2. It is used when we want to extract rows by their numeric index/position instead of
conditions on column values.
3. Unlike filter() (which selects rows based on conditions), slice() works only with
the row number positions.
4. It helps in selecting specific rows (first row, last row, middle rows, or a range of
rows).
5. The output of slice() is always a subset of the original data frame, keeping the
same columns but fewer rows.
6. It is very useful for data sampling, quick checks, or when you need specific row
positions instead of logical conditions.
7. Additional helper functions like slice_head(), slice_tail(), slice_sample(),
and slice_min()/slice_max() are also available in modern dplyr for convenience.
Syntax of slice()
slice(.data, rows)
Parameters:
.data → The data frame or tibble.
rows → Row numbers (as integers) or range of rows you want to select.
Examples
Example 1: Selecting specific rows
library(dplyr)
# Creating a sample data frame
df <- [Link](
ID = 1:6,
Name = c("A", "B", "C", "D", "E", "F"),
Score = c(45, 78, 89, 66, 90, 55)
)
# Select rows 2 and 4
result <- slice(df, c(2, 4))
print(result)
Output:
ID Name Score
1 2 B 78
2 4 D 66
Example 2: Selecting a range of rows
# Select rows from 3 to 5
result <- slice(df, 3:5)
print(result)
Output:
ID Name Score
1 3 C 89
2 4 D 66
3 5 E 90
Example 3: Selecting first and last row
# Select first and last row
result <- slice(df, c(1, n()))
print(result)
Output:
ID Name Score
1 1 A 45
2 6 F 55
Example 4: Using negative indexing
# Exclude row 2
result <- slice(df, -2)
print(result)
Output:
ID Name Score
1 1 A 45
2 3 C 89
3 4 D 66
4 5 E 90
5 6 F 55
👉 In summary, slice() is mainly for row position-based selection in R, whereas filter()
is used for condition-based selection.
Machan, idhu neat ah note format la irukku, direct ah copy panni Word la paste panna
professional notes maari varum.
Unakku venumna naan slice_head(), slice_tail(), slice_sample() kuvum same style
la prepare panniduven.