top_perc: Select Top or Bottom Percentage of Data

View source: R/top_perc.R

top_percR Documentation

Select Top or Bottom Percentage of Data

Description

Selects the top (largest) or bottom (smallest) percentage of data based on specified traits. Positive percentages extract the largest values; negative percentages extract the smallest values.

Usage

top_perc(
  data,
  perc,
  cols,
  by = NULL,
  keep_data = FALSE,
  stats = c("n", "min", "max", "mean", "median", "sd", "se", "cv")
)

Arguments

data

A data.frame or data.table.

perc

A numeric vector strictly between -1 and 1 (excluding 0). Positive values (e.g., 0.05) select the top X% of largest values. Negative values (e.g., -0.1) select the bottom X% of smallest values.

cols

Numeric trait column(s) to analyse, as names or indices.

by

Grouping column(s), as names or indices. Default is NULL.

keep_data

Logical. If TRUE, returns a named list where each element contains both stat (summary statistics) and data (the subset rows). If FALSE (default), returns a single combined data.frame of statistics for all perc values.

stats

Statistics of the selected records, computed exactly as in desc_stats() (same names and definitions). Default c("n", "min", "max", "mean", "median", "sd", "se", "cv"); any of "n", "min", "max", "mean", "median", "q1", "q3", "iqr", "mad", "sd", "se", "ci", "ci_low", "ci_high", "cv", "skew", "kurt".

Details

Ranking uses ties.method = "min", so tied values at the cut-off are all selected and slightly more than the requested share can be returned. Missing values are removed before ranking. Groups with fewer than 1 / abs(perc) non-missing records cannot contribute a single record: they are kept in the summary with n = 0 and a warning is issued.

Value

  • keep_data = FALSE: a data.frame with one row per by / cols / perc combination: the by columns, variable, the requested stats and selection.

  • keep_data = TRUE: a named list (one element per perc value) where each element is a list with $stat and $data.

See Also

desc_stats() for statistics of all records.

Examples

# Example 1: Basic usage with single trait
# This example selects the top 10% of observations based on Petal.Width
# keep_data=TRUE returns both summary statistics and the filtered data
top_perc(iris, 
         perc = 0.1,                # Select top 10%
         cols = c("Petal.Width"),   # Column to analyze
         keep_data = TRUE)          # Return both stats and filtered data

# Example 2: Using grouping with 'by' parameter
# This example performs the same analysis but separately for each Species
# Returns a data.frame of summary statistics, one row per Species
top_perc(iris, 
         perc = 0.1,                # Select top 10%
         cols = c("Petal.Width"),   # Column to analyze
         by = "Species")            # Group by Species

mintyr documentation built on Oct. 5, 2026, 5:08 p.m.