Functions in R language (or any programming language) are fundamental building blocks that allow you to organize the programming code, make it reusable, and perform complex tasks efficiently.

Functions in the R Language are first-class objects of the class function and can be passed by arguments to other functions. Functions can be assigned to variables, stored in a list, passed as arguments to other functions, created functions inside functions, and even returned function as the result of a function. There are three building blocks of functional programming: anonymous functions, closures (functions written by functions), and a list of functions.

Each function in the R Language consists of three components

- formal( )
- body( )
- environment( )

### Types of Function

There are two main types of functions in R:

**Built-in functions in R:**There is a vast library of built-in functions in R Language, like finding the mean (`mean()`

), calculating the sum (`sum()`

), or creating graphs (`plot()`

).**User-defined functions in R:**One can create functions to tailor them to one’s needs. This is useful for repetitive tasks, improving code readability, and avoiding errors.

Each function has arguments that can be given default values, which makes interactive usage more convenient. A function is defined by an assignment of the form

name <- function(arg1, arg2, …){ Expression }

where the expression uses the `arg1, arg2, ...`

(arguments) to calculate a value. The value of the expression is the value returned for the function. A call to function usually takes the form

name(expr1, expr2, …)

and may occur anywhere a function call is legitimate.

### Functions in R Language: Example

As an example, consider the following customized function (user-defined function) `center()`

. This function can compute the mean, median, and trimmed mean of the input data. The `center()`

function has two arguments, the first argument is for data and the second argument is for the selection of summary statistics.

center<-function(x, type){ type == "mean" && return(mean(x)) type == "median" && return(median(x)) type == "trimmed" && return(mean(x, trim=0.1)) }

As another example, the user-defined summary( ) function is created without repetition of some arguments, i.e. duplication is removed. Note that all the functions in the user-defined function are stored as a list.

summary <- function(x) { funs <- c(mean, median, sd, mad, IQR) lapply(funs, function(f) f(x, na.rm = TRUE)) }

The center() function is created to perform some summary statistics using the switch() statement.

center<-function(x, type){ switch(type, mean = mean(x), median = median(x), trimmed = mean(x,trim=0.1) ) }

Let us generate the data from normal distribution and check the output from the user-defined function center().

x <- rnorm(100) center(x, type="mean") center(x, type="median") center(x, type="trimmed") center(x, type="mode")