June 2007
Beginner to intermediate
950 pages
27h 8m
English
When you want a function to do different things in different circumstances, then the switch function can be useful. Here we write a function that can calculate any one of four different measures of central tendency: arithmetic mean, geometric mean, harmonic mean or median (p. 51). The character variable called measure should take one value of Mean, Geometric, Harmonic or Median; any other text will lead to the error message Measure not included. Alternatively, you can specify the number of the switch (e.g. 1 for Mean, 4 for Median).
central<-function(y, measure) { switch(measure, Mean = mean(y), Geometric = exp(mean(log(y))), Harmonic = 1/mean(1/y), Median = median(y), stop("Measure not included")) }
Note that you have to include the character strings in quotes as arguments to the function, but they must not be in quotes within the switch function itself.
central(rnorm(100,10,2),"Harmonic") [1] 9.554712 central(rnorm(100,10,2),4) [1] 10.46240
Read now
Unlock full access