The Switch Operator in R

Master R

By Guangming Lang Comment

The switch() function in R is very powerful and here’s an example.

center = function(x, type) {
        # Finds the center of x
        #
        # Args:
        #       x:      numeric vector
        #       type:   string specifying center type
        # 
        # Returns:
        #       the specified center of x
        switch(type,
               mean = mean(x), median = median(x), trimmed = mean(x, trim=0.1))
}

# unit test
x = rcauchy(10)
center(x, "mean")
## [1] -1.237765
center(x, "median")
## [1] -0.9514988
center(x, "trimmed")
## [1] -1.082965

If you enjoyed this post, get updates. It's FREE