Learn R Programming

regressinator (version 0.2.0)

by_level: Convert factor levels to numeric values

Description

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, ...)

Value

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

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.

See Also

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

Examples

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

by_level(foo, spam = 4, ham = 10, ducks = 16.7)

by_level(foo, c("spam" = 4, "ham" = 10, "ducks" = 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)

Run the code above in your browser using DataLab