Saturday 18 July 2015

R: functions

In programming, functions are blocks of code that perform a number of pre-defined commands to achieve something productive. “function” directive is used to create functions in R. Function in R are objects, just like vectors, matrices etc., Since functions are objects, they can be passed as parameters to other functions.

Functions can be nested in R. You can define one function inside other function.

How to define a function
functionName <- function(p1, p2, ..pN){
         Do Something
}

p1, p2, .. pN are parameters passed to the function. Parameters are optional.


FunctionEx.R
add <- function(x, y){
  return(x+y)
}

sub <- function(x, y){
  return(x-y)
}

mul <- function(x, y){
  return(x*y)
}

div <- function(x, y){
  return(x/y)
}

addition <- add(20, 10)
subtraction <- sub(20, 10)
multiplication <- mul(20, 10)
division <- div(20, 10)

sprintf("Addition of 20, 10 is %d", addition)
sprintf("subtraction of 20, 10 is %d",subtraction)
sprintf("multiplication of 20, 10 is %d",multiplication)
sprintf("division of 20, 10 is %d",division)


$ Rscript FunctionEx.R 
[1] "Addition of 20, 10 is 30"
[1] "subtraction of 20, 10 is 10"
[1] "multiplication of 20, 10 is 200"
[1] "division of 20, 10 is 2"


“return” statement is used to return the value to caller.

Note
If you don’t specify return statement in a function, then function returns last evaluated expression of function body.




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment