Creating new functions

There are two different types of functions in R, user-defined functions and built-in functions.

User-defined functions

A user-defined function provides customization and flexibility to users to write their functions to perform computations. It has a general notation shown as follows:

newFunc <- function(x){define function}
> int<-seq(1:20)
> int
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
> myfunc<-function(x){x*x}
> myfunc(int)
 [1]   1   4   9  16  25  36  49  64  81 100 121 144 169 196 225 256 289 324
     361 400

In the preceding script, we are creating a small sequence of numbers from 1 to 20 and a user-defined function to calculate the square of each integer. Using the new function, we can calculate the square of any number. So the user can define and create his or her own custom function.

Built-in functions

Built-in functions, such as mean, median, standard deviation, and so on, provide the user the ability to compute basic statistics using R. There are many built-in functions; the following table displays a few important built-in functions:

Function

Description

abs(x)

Absolute value

sqrt(x)

Square root

ceiling(x)

Rounding up the number

floor(x)

Rounding down the number

trunc(x)

trunc(5.99) is 5

round(x, digits=n)

round(3.475, digits=2) is 3.48

signif(x, digits=n)

signif(3.475, digits=2) is 3.5

cos(x), sin(x), tan(x)

Also acos(x), cosh(x), acosh(x), and so on

log(x)

Natural logarithm

log10(x)

Common logarithm

exp(x)

e^x

Table 2: Some built-in functions

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

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