R: User-defined function

Functions in a Programming Language are sets of instruction. It is the collection of instructions or statements that work together to do a certain task. R used function as an objects.

In R interpreter passes the control to function along with the arguments required. After the function has achieved its goal it gives back the control to the interpreter.  Functions helps in reducing the complexity of the program and it also avoid repetitions.

In R programming, user-defined functions are functions created by the user to perform certain instructions.If we need certain function which can be reused which is not available in R, then we can create it on our own.

Create a User-Defined Function

We can easily create any function by using following syntax:

Function_name <- function(arguments)
   return (return)

Where function _name is the name of the function, arguments is the input argument needed by the function, function_body is the body of the function, return is the return value of the function.


user_defined_function <-function(a)
    for(i in 1:a)
         b <- i*2

user_defined_function (6)


[1] 2 
[1] 4 
[1] 6 
[1] 8 
[1] 10 
[1] 12