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 are 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.
  • Built-in function - predefined functions called by users.




User Defined functions

We can define our own function using the function(), and the function name should be unique because two functions cannot be of the same name, if we do so, then it will return an error. We can pass one or more parameters or no parameters 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 returns the 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 the function and calling the function should be same.

Scope of the function

The variable defined outside of the 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 a rich set of built-in functions that make our development so easy. The R functions cover all small to small and large to large tasks manipulations. Like to get the substring of a string, functions to handle a string like to convert a string in uppercase or lowercase, or to get the 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.







Read more articles


General Knowledge



Learn Popular Language