Repository navigation
Expand file tree
/
Copy pathtop_n.Rd
More file actions
66 lines (57 loc) · 1.74 KB
/
Copy pathtop_n.Rd
File metadata and controls
66 lines (57 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/top-n.R
\name{top_n}
\alias{top_n}
\alias{top_frac}
\title{Select top (or bottom) n rows (by value)}
\usage{
top_n(x, n, wt)
top_frac(x, n, wt)
}
\arguments{
\item{x}{a \code{\link[=tbl]{tbl()}} to filter}
\item{n}{number of rows to return for \code{top_n()}, fraction of rows to
return for \code{top_frac()}.
If \code{x} is grouped, this is the
number (or fraction) of rows per group. Will include more rows if
there are ties.
If \code{n} is positive, selects the top rows. If negative,
selects the bottom rows.}
\item{wt}{(Optional). The variable to use for ordering. If not
specified, defaults to the last variable in the tbl.}
}
\description{
This is a convenient wrapper that uses \code{\link[=filter]{filter()}} and
\code{\link[=min_rank]{min_rank()}} to select the top or bottom entries in each group,
with respect to \code{wt}. Note, the resulting data frame will not be
ordered or sorted.
}
\details{
Both \code{n} and \code{wt} are automatically \link[rlang:enquo]{quoted} and later
\link[rlang:eval_tidy]{evaluated} in the context of the data
frame. It supports \link[rlang:quasiquotation]{unquoting}.
}
\examples{
df <- data.frame(x = c(6, 4, 1, 10, 3, 1, 1))
df \%>\% top_n(2)
# half the rows
df \%>\% top_n(n() * .5)
df \%>\% top_frac(.5)
# Negative values select bottom from group. Note that we get more
# than 2 values here because there's a tie: top_n() either takes
# all rows with a value, or none.
df \%>\% top_n(-2)
if (require("Lahman")) {
# Find 10 players with most games
tbl_df(Batting) \%>\%
group_by(playerID) \%>\%
tally(G) \%>\%
top_n(10)
# Find year with most games for each player
\dontrun{
tbl_df(Batting) \%>\%
group_by(playerID) \%>\%
top_n(1, G)
}
}
}