R Functions

A function is a way of wrapping up a piece of code and giving that chunk a name, so that you can utilize that piece later in just one line of code. Functions are most valuable when you will utilize the code in more than one place, but they can be helpful even in one-use situations, because they can make your code much more readable.

Function definition syntax

Function definition has the following structure:

function_name <- function(arg1, arg2,..argn)
{
	statements
}

That is, function definitions have four parts -

  • The special word function.
  • The name that you want to give your function.
  • The function's argument lists separated by commas.
  • The function body contains a brace-enclosed set of statements with a return statement.

Types of functions in R.

  • User defined function - functions defined by users.
  • Builtin function - predefined functions call by users.




User Defined functions

We can define our own function using function(), and the function name should be unique because two functions cannot be of the same name, if we will do so then it will return an error. We can pass one or more parameter or no parameter in a function according to the requirement. Function statement start and stop with curly braces. The statement inside a function processes the some operations as we mention on the parameters and return processing result. A function statement ends with a return statement.

Example -

In the example below, we create a function name z(), that gets the hypotenuse.

> z <- function(x=7, y=5)
+ {
+ sqrt(x^2 + y^2)
+ }
> z()
[1] 8.602325
> 

We can call this addition function anywhere in the code, where there is need to get hypotenuse.
The number of parameters in defining function and call function should be same.

Scope of the function

The variable defined outside of function cannot be used inside the function, to make use of this variable inside the function, we will have to pass this as a parameter. Similarly, the variable defined inside the function cannot be called outside.


Built In function call

R has rich set of builtin functions that make our development so easy. The R functions cover all small to small and large to large tasks manipulations. Like to get substring of a string, functions to handle string like to convert a string in uppercase or lowercase, or to get substring of a string, functions to perform on arrays and also functions used in some advanced applications like, music manipulations, credit card processing, file compression etc.