calc_quantiles: Calculate and insert columns containing arbitrary quantiles...

View source: R/calc-quantiles.R

calc_quantilesR Documentation

Calculate and insert columns containing arbitrary quantiles for a particular column

Description

Calculate and insert columns containing arbitrary quantiles for a particular column

Calculate quantiles across groups for a given column

Usage

calc_quantiles(
  df = NULL,
  col = NULL,
  probs = c(0.05, 0.25, 0.5, 0.75, 0.95),
  include_mean = FALSE
)

calc_quantiles_by_group(
  df = NULL,
  grp_cols = NULL,
  cols = NULL,
  cols_rm = "posterior",
  grp_names = grp_cols,
  probs = c(0.025, 0.5, 0.975),
  include_mean = FALSE
)

Arguments

df

A data.frame with columns with names given by grp_cols and col

col

A column name on which to perform the calculations. Must be in df or an error will be thrown

probs

A vector of quantiles to pass to stats::quantile()

include_mean

If TRUE, include the mean in the output

grp_cols

A vector of column names to use for grouping the data

cols

The column names to use as values to calculate quantiles for. If NULL, all columns not in grp_cols will be calculated and the quantiles will appear in a column

cols_rm

A vector of names of columns to remove from the calculations. Only used if cols is NULL

grp_names

The column namesto use for labeling the grouped columns. By default it is the same as the grouping columns (grp_cols).

Value

A data.frame with a new column for each value in the probs vector

A data.frame containing the quantile values with one row per group represented by grp_cols

Examples

library(tibble)
library(dplyr)
library(purrr)
pq <- tribble(
  ~year, ~grp, ~val,
  2000,    1,  2.1,
  2001,    1,  3.4,
  2002,    1,  4.5,
  2003,    1,  5.6,
  2004,    1,  6.7,
  2000,    2,  3.1,
  2001,    2,  4.4,
  2002,    2,  5.5,
  2003,    2,  6.6,
  2004,    2,  8.7,
  2000,    3, 13.1,
  2001,    3, 14.4,
  2002,    3, 15.5,
  2003,    3, 16.6,
  2004,    3, 18.7)

probs <- c(0.05, 0.25, 0.5, 0.75, 0.95)

yrs <- sort(unique(pq$year))
df <- pq %>%
  group_by(year) %>%
  group_map(~ calc_quantiles(.x, col = "val", probs = probs)) %>%
  map_df(~{.x}) %>%
  mutate(year = yrs) %>%
  select(year, everything())

pbs-assess/gfiscamutils documentation built on Oct. 24, 2024, 1:37 p.m.