Replace each entry in a vector with its corresponding numeric value, for instance to use a factor variable to specify intercepts for different groups in a regression model.

## Usage

by_level(x, ...)

## Arguments

x

Vector of factor values

...

Mapping from factor levels to values. Can be provided either as a series of named arguments, whose names correspond to factor levels, or as a single named vector.

## Value

Named vector of same length as x, with values replaced with those specified. Names are the original factor level name.

rfactor() to draw random factor levels, and the forcats package https://forcats.tidyverse.org/ for additional factor manipulation tools

## Examples

foo <- factor(c("spam", "ham", "spam", "ducks"))

by_level(foo, spam = 4, ham = 10, ducks = 16.7)
#>  spam   ham  spam ducks
#>   4.0  10.0   4.0  16.7

by_level(foo, c("spam" = 4, "ham" = 10, "ducks" = 16.7))
#>  spam   ham  spam ducks
#>   4.0  10.0   4.0  16.7

# to define a population with a factor that affects the regression intercept
intercepts <- c("foo" = 2, "bar" = 30, "baz" = 7)
pop <- population(
group = predictor("rfactor",
levels = c("foo", "bar", "baz"),
prob = c(0.1, 0.6, 0.3)),
x = predictor("runif", min = 0, max = 10),
y = response(by_level(group, intercepts) + 0.3 * x,
error_scale = 1.5)
)
sample_x(pop, 5)
#> Sample of 5 observations from
#> Population with variables:
#> group: rfactor(list(levels = c("foo", "bar", "baz"), prob = c(0.1, 0.6, 0.3)))
#> x: runif(list(min = 0, max = 10))
#> y: gaussian(by_level(group, intercepts) + 0.3 * x, error_scale = 1.5)
#>
#> # A tibble: 5 × 2
#>   group     x
#> * <fct> <dbl>
#> 1 foo   3.54
#> 2 bar   0.947
#> 3 foo   3.99
#> 4 baz   5.81
#> 5 bar   7.39