fslice | R Documentation |
A fast function to extract rows from a matrix or data frame-like object (by groups).
fslice(x, ..., n = 1, how = "first", order.by = NULL,
na.rm = .op[["na.rm"]], sort = FALSE, with.ties = FALSE)
fslicev(x, cols = NULL, n = 1, how = "first", order.by = NULL,
na.rm = .op[["na.rm"]], sort = FALSE, with.ties = FALSE, ...)
x |
a matrix, data frame or list-like object, including 'grouped_df'. |
... |
for |
cols |
select columns to group by, using column names, indices, a logical vector or a selector function (e.g. |
n |
integer or proportion (if < 1). Number of rows to select from each group. If a proportion is provided, it is converted to the equivalent number of rows. |
how |
character. Method to select rows. One of:
|
order.by |
vector or column name to order by when |
na.rm |
logical. If |
sort |
logical. If |
with.ties |
logical. If |
A subset of x
containing the selected rows.
fsubset
, fcount
, Data Frame Manipulation, Collapse Overview
# Basic usage
fslice(mtcars, n = 3) # First 3 rows
fslice(mtcars, n = 3, how = "last") # Last 3 rows
fslice(mtcars, n = 0.1) # First 10% of rows
# Using order.by
fslice(mtcars, n = 3, how = "min", order.by = mpg) # 3 cars with lowest mpg
fslice(mtcars, n = 3, how = "max", order.by = mpg) # 3 cars with highest mpg
# With grouping
mtcars |> fslice(cyl, n = 2) # First 2 cars per cylinder
mtcars |> fslice(cyl, n = 2, sort = TRUE) # with sorting (slightly less efficient)
mtcars |> fslice(cyl, n = 2, how = "min", order.by = mpg) # 2 lowest mpg cars per cylinder
# Using with.ties
mtcars |> fslice(cyl, n = 1, how = "min", order.by = mpg, with.ties = TRUE)
# With grouped data
mtcars |>
fgroup_by(cyl) |>
fslice(n = 2, how = "max", order.by = mpg) # 2 highest mpg cars per cylinder
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.