Function in R Programming Language
Table of Content:
Writing functions is a core activity of an R programmer. It represents the key
step of the transition from a mere “user” to a developer who creates
new functionality for R. Functions are often used to encapsulate a sequence of
expressions that need to be executed numerous times, perhaps under slightly
different conditions. Functions are also often written when code must be shared
with others or the public.
The writing of a function allows a developer to
create an interface to the code, that is explicitly specified with a set of parameters.
This interface provides an abstraction of the code to potential users. This abstraction
simplifies the users’ lives because it relieves them from having to know
every detail of how the code operates. In addition, the creation of an interface
allows the developer to communicate to the user the aspects of the code that are
important or are most relevant.
Functions in R
Functions in R are “first class objects”, which means that
they can be treated much like any other R object. Importantly,
• Functions
can be passed as arguments to other functions. This is very handy for the various apply
funtions, like lapply() and sapply() .
• Functions can be nested, so that you
can define a function inside of another function If you’re familiar with common
language like C, these features might appear a bit strange. However, they are really
important in R and can be useful for data analysis.
Function Definition
An R function is created by using the keyword function. The basic syntax of an R function definition is as follows −
function_name <- function(arg_1, arg_2, ...) { Function body }
Function Components
The different parts of a function are −
-
Function Name − This is the actual name of the function. It is stored in R environment as an object with this name.
-
Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values.
-
Function Body − The function body contains a collection of statements that defines what the function does.
-
Return Value − The return value of a function is the last expression in the function body to be evaluated.
R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions.