x_at_y: Generate lookup vectors for composing nested indices

View source: R/x_at_y.R

x_at_yR Documentation

Generate lookup vectors for composing nested indices

Description

Generates a lookup vector such that x_at_y(x, y)[y] == x. Particularly useful for generating lookup tables for nested indices in conjunction with compose_data().

Usage

x_at_y(x, y, missing = NA)

Arguments

x

Values in the resulting lookup vector. There should be only one unique value of x for every corresponding value of y.

y

Keys in the resulting lookup vector. Should be factors or integers.

missing

Missing levels from y will be filled in with this value in the resulting lookup vector. Default NA.

Details

x_at_y(x, y) returns a vector k such that k[y] == x. It also fills in missing values in y: if y is an integer, k will contain entries for all values from 1 to max(y); if y is a factor, k will contain entries for all values from 1 to nlevels(y). Missing values are replaced with missing (default NA).

Author(s)

Matthew Kay

See Also

compose_data().

Examples


library(magrittr)

df = data.frame(
  plot = factor(paste0("p", rep(1:8, times = 2))),
  site = factor(paste0("s", rep(1:4, each = 2, times = 2)))
)

# turns site into a nested index: site[p] gives the site for plot p
df %>%
  compose_data(site = x_at_y(site, plot))


tidybayes documentation built on Aug. 13, 2023, 1:06 a.m.