slice()
lets you index rows by their (integer) locations. It allows you
to select, remove, and duplicate rows. It is accompanied by a number of
helpers for common use cases:
slice_head()
and slice_tail()
select the first or last rows.
slice_sample()
randomly selects rows.
slice_min()
and slice_max()
select rows with the smallest or largest
values of a variable.
If .data
is a grouped_df, the operation will be performed on each group,
so that (e.g.) slice_head(df, n = 5)
will select the first five rows in
each group.
# S3 method for class 'SummarizedExperiment'
slice(.data, ..., .preserve = FALSE)
A data frame, data frame extension (e.g. a tibble), or a lazy data frame (e.g. from dbplyr or dtplyr). See Methods, below, for more details.
For slice()
: <data-masking
>
Integer row values.
Provide either positive values to keep, or negative values to drop. The values provided must be either all positive or all negative. Indices beyond the number of rows in the input are silently ignored.
For slice_*()
, these arguments are passed on to methods.
Relevant when the .data
input is grouped.
If .preserve = FALSE
(the default), the grouping structure
is recalculated based on the resulting data, otherwise the grouping is kept as is.
An object of the same type as .data
. The output has the following
properties:
Each row may appear 0, 1, or many times in the output.
Columns are not modified.
Groups are not modified.
Data frame attributes are preserved.
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()
.
These function are generics, which means that packages can provide implementations (methods) for other classes. See the documentation of individual methods for extra arguments and differences in behaviour.
Methods available in currently loaded packages:
slice()
: (ANY
, integer
, numeric
, Rle
, RleList
, XDouble
, XInteger
), dplyr (data.frame
), plotly (plotly
), tidySummarizedExperiment (SummarizedExperiment
)
.
slice_head()
: dplyr (data.frame
)
.
slice_tail()
: dplyr (data.frame
)
.
slice_min()
: dplyr (data.frame
)
.
slice_max()
: dplyr (data.frame
)
.
slice_sample()
: dplyr (data.frame
)
.
Hutchison, W.J., Keyes, T.J., The tidyomics Consortium. et al. The tidyomics ecosystem: enhancing omic data analyses. Nat Methods 21, 1166–1170 (2024). https://doi.org/10.1038/s41592-024-02299-2
Wickham, H., François, R., Henry, L., Müller, K., Vaughan, D. (2023). dplyr: A Grammar of Data Manipulation. R package version 2.1.4, https://CRAN.R-project.org/package=dplyr
data(pasilla)
pasilla |> slice(1)
#> class: SummarizedExperiment
#> dim: 1 1
#> metadata(1): latest_join_scope_report
#> assays(1): counts
#> rownames(1): FBgn0000003
#> rowData names(0):
#> colnames(1): untrt1
#> colData names(2): condition type