Switch
Rather then string together multiple if - else if chains, you can often use switch
.
centre <- function(x, type) {
switch(type,
mean = mean(x),
median = median(x),
trimmed = mean(x, trim = .1),
stop("Invalid `type` value")
)
}
Last component should always throw an error, as unmatched inputs would otherwise invisibly return NULL.
Book recommends to only use character inputs for switch()
.
vec <- c(1:20,50:55)
centre(vec, "mean")
#> [1] 20.19231
centre(vec, "median")
#> [1] 13.5
centre(vec, "trimmed")
#> [1] 18.77273
set.seed(123)
x <- rlnorm(100)
centers <- data.frame(type = c('mean', 'median', 'trimmed'))
centers$value = sapply(centers$type, \(t){centre(x,t)})
require(ggplot2)
ggplot(data = data.frame(x), aes(x))+
geom_density()+
geom_vline(data = centers,
mapping = aes(color = type, xintercept = value),
linewidth=0.5,linetype="dashed") +
xlim(-1,10)+
theme_bw()
Example from book of “falling through” to next value