Working with functions

Functions are the core of R, and they are useful to structure and modularize code. We have already seen some functions in the preceding section. These functions can be considered built-in functions that are available on the basis of R or where we install some packages.

On the other hand, we can define and create our own functions based on different operations and computations we want to perform on the data. We will create functions in R using the function() directive, and these functions will be stored as objects in R.

Here is what the structure of a function in R looks like:

myfunction <- function(arg1, arg2, … )
{
statements
return(object)
}

The objects specified under a function as local to that function and the resulting objects can have any data type. We can even pass these functions as arguments for other functions.

Functions in R support nesting, which means that we can define a function within a function and the code will work just fine.

The resulting value of a function is known as the last expression evaluated on execution.

Once a function is defined, we can use that function using its name and passing the required arguments.

Let's create a function named squaredNumwhich calculates the square value of a number:

squaredNum<-function(number)
{
a<-number^2
return(a)
}

Now, we can calculate the square of any number using the function that we just created:

squaredNum(425)
## [1] 180625

As we move on in this book, we will see how important such user-defined functions are.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.8.162