top_n: Select top [or bottom] n rows [by value]
In dplyr: A Grammar of Data Manipulation
Description Usage Arguments Examples
View source: R/top-n.R
Description
top_n[] was superseded because the name was fundamentally confusing as it returned what you might reasonably consider to be the bottom rows. Additionally, the wt variable had a confusing name, and strange default [the last column in the data frame]. Unfortunately we could not see an easy way to fix the existing top_n[] function without breaking existing code, so we created a new alternative.
Usage
1 2 3 | top_n[x, n, wt] top_frac[x, n, wt] |
Arguments
x | A data frame. |
n | Number of rows to return for top_n[], fraction of rows to return for top_frac[]. If n is positive, selects the top rows. If negative, selects the bottom rows. If x is grouped, this is the number [or fraction] of rows per group. Will include more rows if there are ties. |
wt | [Optional]. The variable to use for ordering. If not specified, defaults to the last variable in the tbl. |
Examples
1 2 3 4 5 6 7 8 9 10 11 12 | df % top_n[2] # highest values df %>% top_n[-2] # lowest values # now use df %>% slice_max[x, n = 2] df %>% slice_min[x, n = 2] # top_frac[] -> prop argument of slice_min[]/slice_max[] df %>% top_frac[.5] # -> df %>% slice_max[x, prop = 0.5] |
Example output
Attaching package: dplyr The following objects are masked from package:stats: filter, lag The following objects are masked from package:base: intersect, setdiff, setequal, union Selecting by x x 1 6 2 10 Selecting by x x 1 1 2 1 3 1 x 1 10 2 6 x 1 1 2 1 3 1 Selecting by x x 1 6 2 4 3 10 x 1 10 2 6 3 4
dplyr documentation built on Feb. 8, 2022, 5:15 p.m.
Related to top_n in dplyr...
dplyr index
Package overview README.md Column-wise operations dplyr base R dplyr compatibility Grouped data Introduction to dplyr Programming with dplyr Row-wise operations Two-table verbs Window functions