Section 3 Function: Examples

3.1 Function: Power

  • Create a function to calculate power of elements of a numeric vector

3.2 Function: Mean (AM, GM, HM)

  • Calculate AM, GM and HM of a numeric vector using the following formula.

Arithmetic Mean (AM)

\[ \large AM = (x_1 + x_2 + ... + x_n)/n = \frac{1}{n}\sum\limits_{i=1}^{n} x_{i}\]

Geometric Mean (GM)

\[ \large GM = \sqrt[n]{(x_1 x_2 ... x_n)} = \left( \prod \limits_{i=1}^{n} x_{i} \right) ^{\frac{1}{n}} \]

Harmonic Mean (HM)

\[ \large HM = \frac{n}{(\frac{1}{x_1} + \frac{1}{x_2} + ... + \frac{1}{x_n})} = \frac{1}{\frac{1}{n}\sum\limits_{i=1}^{n} \frac{1}{x_i}}\]


3.3 Function: Variance & Standard Deviation

  • Use the above data to calculate sample variance and standard deviation.

Sample Variance

\[ \large Var(x) = s_x^2 = \frac{1}{n-1}\sum\limits_{i=1}^{n} (x_i-\bar{x})^2 \]

Sample Standard Deviation

\[ \large s_x = \sqrt{s_x^2} = \sqrt{Var(x)} \]


3.4 Function: Summary Statistics

  • Use base R functions or your own custom functions, write a function that will return a vector summary statistics of the following location and dispersion estimates of a numeric :
  • Number of observations
  • Number of non-missing observations
  • Minimum value (Min)
  • Maximum value (Max)
  • Arithmetic mean (AM)
  • Geometric mean (GM)
  • Harmonic mean (HM)
  • First quartile (Q1)
  • Second quartile or Median (Q2)
  • Third quartile (Q3)
  • Range
  • Interquartile range (IQR)
  • Variance (Var)
  • Standard deviation (SD)
  • Coefficient of variation (CV)