Aim of the Unit

This Unit aims to Write user-defined functions

Define a new function

A new function is defined with the following synthax:

function_name <- function(x) { ... }

where:

• function_name is the name of the function
• function() function call
• x is the argument
• {...} space for typing the function

For instance, let’s define a new function that calculate the coeffient of variation or “CV”. This is determined as:

$CV=\frac{\text{standard deviation}}{\text{mean}}$

This algorithm $CV=\frac{s}{\overline{x}}$$CV = \dfrac{s}{\bar{x}}$ can be implemented in a user-defined function in the following way:

CV = function(x) {sd(x)/mean(x)}

Now, having defined the following vector:

A <- c(5,4,6,4,5,4,6,3)

Let’apply the function CV:

CV(A)
## [1] 0.2293319