# R – Functions

R Function consist of 4 parts:

• Formals () – list of argument supplied to function
• Environment () –which stores the function name as an object
• Body () – contains list of statements that decides the task of this function name
• Return() – it returns the result of function call immediately from the function.

Example:

> func_name <- function(a)

+ a=10

> func_name <- function(a)a=10

> environment(func_name)

<environment: R_GlobalEnv>

> body(func_name)

a = 10

> formals(func_name)

\$a

> check <- function(t) {

+ if (t == red) {

+ return(“STOP”)

+ }

+ else if (t ==green) {

+ return(“GO”)

+ }

+ else {

+ return(“WAIT”)

+ }

+ }

R Functions are of 2 types:

• User defined function
• Built-in function

User Defined Function:

One of the useful feature of R programming is its ability to allow programmer to create user defined functions.

Example

Here I am defining a function “fun” which will add 2 numbers

> fun <- function (a, b) {

+ a + b

+ }

> fun (5, 12)

 17

Built-in Functions:

R programming comes up with a number of built in functions. Mostly they are of the following types:

• Numeric Functions
• Character Functions
• Statistical Functions

Numeric Functions:

• Floor(x) – floor (5.7) gives 5
• Ceiling(x) – ceiling (5.2) gives 6
• Trunc(x) – trunc(2.137) gives 2
• Abs(x) – abs(-3.4) gives 3.4
• Sqrt(x) – sqrt(25) gives 5
• Round(x, digit=n) – round(2.137, digit=2) gives 2.14
• Log(x) – log(5) gives natural logarithm of 5 which is 1.609438
• Log10(x) – log10(5) gives common logarithm of 5 which is 0.69897
• Sum(x) – sum (5 +6) gives 11

Character Functions

• Toupper(x) – toupper(“RamEswaRam”) gives “RAMESWARAM”
• Tolower(x) – tolower(“RamEswaRam”) gives “rameswaram”
• Grep() –used for keyword search.
• > str <-c(“are” ,”Delaware is a malware”,” But its not a hardware”)
• > total <- grep (“are”, str, value=F)
• > total
•  1 2 3
• sub()—used for keyword substitution
• > total <- sub (“are”,”aks”, str)
• > total
•  “aks”                     “Delawaks is a malware”
•  ” But its not a hardwaks”

Statistical Functions:

• mean ()
• median ()
• mode ()
• min ()
• max ()
• range()
• sd()