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()
.
x_at_y(x, y, missing = NA)
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
).
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))
#> $plot
#> [1] 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
#>
#> $n_plot
#> [1] 8
#>
#> $site
#> [1] 1 1 2 2 3 3 4 4
#>
#> $n_site
#> [1] 4
#>
#> $n
#> [1] 16
#>