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.
Value
Named vector of same length as x, with values replaced with those
specified. Names are the original factor level name.
See also
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 bar 4.98
#> 2 baz 0.195
#> 3 bar 0.872
#> 4 bar 9.96
#> 5 bar 9.42