This function returns the "typical" value of a variable.

typical_value(x, fun = "mean", weights = NULL, ...)

Arguments

x

A variable.

fun

Character vector, naming the function to be applied to x. Currently, "mean", "weighted.mean", "median" and "mode" are supported, which call the corresponding R functions (except "mode", which calls an internal function to compute the most common value). "zero" simply returns 0. Note: By default, if x is a factor, only fun = "mode" is applicable; for all other functions (including the default, "mean") the reference level of x is returned. For character vectors, only the mode is returned. You can use a named vector to apply other different functions to integer, numeric and categorical x, where factors are first converted to numeric vectors, e.g. fun = c(numeric = "median", factor = "mean"). See 'Examples'.

weights

Name of variable in x that indicated the vector of weights that will be applied to weight all observations. Default is NULL, so no weights are used.

...

Further arguments, passed down to fun.

Value

The "typical" value of x.

Details

By default, for numeric variables, typical_value() returns the mean value of x (unless changed with the fun-argument).

For factors, the reference level is returned or the most common value (if fun = "mode"), unless fun is a named vector. If fun is a named vector, specify the function for integer, numeric and categorical variables as element names, e.g. fun = c(integer = "median", factor = "mean"). In this case, factors are converted to numeric values (using to_value) and the related function is applied. You may abbreviate the names fun = c(i = "median", f = "mean"). See also 'Examples'.

For character vectors the most common value (mode) is returned.

Examples

data(iris)
typical_value(iris$Sepal.Length)
#> [1] 5.843333

library(purrr)
map(iris, ~ typical_value(.x))
#> $Sepal.Length
#> [1] 5.843333
#> 
#> $Sepal.Width
#> [1] 3.057333
#> 
#> $Petal.Length
#> [1] 3.758
#> 
#> $Petal.Width
#> [1] 1.199333
#> 
#> $Species
#> [1] "setosa"
#> 

# example from ?stats::weighted.mean
wt <- c(5,  5,  4,  1) / 15
x <- c(3.7, 3.3, 3.5, 2.8)

typical_value(x, fun = "weighted.mean")
#> [1] 3.325
typical_value(x, fun = "weighted.mean", weights = wt)
#> [1] 3.453333

# for factors, return either reference level or mode value
set.seed(123)
x <- sample(iris$Species, size = 30, replace = TRUE)
typical_value(x)
#> [1] "setosa"
typical_value(x, fun = "mode")
#> [1] "versicolor"

# for factors, use a named vector to apply other functions than "mode"
map(iris, ~ typical_value(.x, fun = c(n = "median", f = "mean")))
#> $Sepal.Length
#> [1] 5.8
#> 
#> $Sepal.Width
#> [1] 3
#> 
#> $Petal.Length
#> [1] 4.35
#> 
#> $Petal.Width
#> [1] 1.3
#> 
#> $Species
#> [1] 2
#>