R Functions - 06
R Functions - 06
R Programming Functions
Class 08
Presented by
Dr. Selvi C
Assistant
Professor
IIIT Kottayam
R Functions
• A set of statements which are organized together to perform a specific task is known
as a function. R provides a series of in-built functions, and it allows the user to create
their own functions. Functions are used to perform tasks in the modular approach.
• Functions are used to avoid repeating the same task and to reduce complexity. To
understand and maintain our code, we logically break it into smaller parts using the
function. A function should be
• Written to carry out a specified task.
• May or may not have arguments
• Contain a body in which our code is written.
• May or may not return one or more output values.
• "An R function is created by using the keyword function." There is the following
syntax of R function:
2
Components of Functions
• There are four components of function, which are as follows:
Function Name
The function name is the actual name of the function. In R, the
function is stored as an object with its name.
Arguments
In R, an argument is a placeholder. In function, arguments are
optional means a function may or may not contain arguments, and
these arguments can have default values also. We pass a value to
the argument when a function is invoked.
Function Body
The function body contains a set of statements which defines what
the function does.
Return value
It is the last expression in the function body which is to be
evaluated.
3
Function Types
• Similar to the other languages, R also has two types of
function, i.e. Built-in Function and User-defined Function.
In R, there are lots of built-in functions which we can directly
call in the program without defining them. R also allows us to
create our own functions.
4
Built-in function
• The functions which are already created or defined in the programming
framework are known as built-in functions. User doesn't need to create
these types of functions, and these functions are built into an application.
End-users can access these functions by simply calling it. R have different
types of built-in functions such as seq(), mean(), max(), and sum(x) etc.
5
User-defined function
• R allows us to create our own function in our program. A user defines a
user-define function to fulfill the requirement of user. Once these
functions are created, we can use these functions like in-built function.
6
Function calling with an argument
7
Function calling with no argument
8
Function calling with Argument
Values
9
Function calling with default
arguments
• To get the default result, we assign the value to the arguments in the function definition,
and then we call the function without supplying argument. If we pass any argument in
the function call, then it will get replaced with the default value of the argument in the
function definition.
10
Nested Functions
• There are two ways to create a nested function:
• Call a function within another function.
• Write a function within a function.
11
Nested Functions
12
Recursion
• R also accepts function recursion, which means a defined function can call itself.
• Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.
• The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory
or processor power. However, when written correctly, recursion can be a very efficient
and mathematically-elegant approach to programming.
• In this example, tri_recursion() is a function that we have defined to call itself
("recurse"). We use the k variable as the data, which decrements (-1) every time we
recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).
• To a new developer it can take some time to work out how exactly this works, best way
to find out is by testing and modifying it.
13
Example
14
R Global Variables
• Variables that are created outside • If you create a variable with the same name inside a
of a function are known function, this variable will be local, and can only be
as global variables. used inside the function. The global variable with
the same name will remain as it was, global and with
• Global variables can be used by the original value.
everyone, both inside of functions
and outside.
15
The Global Assignment Operator
• Normally, when you create a variable inside a function, that variable is local, and can
only be used inside that function.
• To create a global variable inside a function, you can use the global
assignment operator <<-
16
Example
17
R Built-in Functions
• The functions which are already created or defined in the programming framework are
known as a built-in function. R has a rich set of functions that can be used to perform
almost every task for the user. These built-in functions are divided into the following
categories based on their functionality.
18
Math Functions
• R provides the various mathematical functions to perform the mathematical calculation. These
mathematical functions are very helpful to find absolute value, square value and much more
calculations. In R, there are the following functions which are used:
S. No Function Description Example
3. ceiling(x) It returns the smallest integer which is larger than or x<- 4.5 print(ceiling(x)) Output[1] 5
equal to x.
4. floor(x) It returns the largest integer, which is smaller than or x<- 2.5 print(floor(x)) Output[1] 2
equal to x.
5. trunc(x) It returns the truncate value of input x. x<- c(1.2,2.5,8.1) print(trunc(x)) Output[1] 1 2 8
7. cos(x), sin(x), It returns cos(x), sin(x) value of input x. x<- 4 print(cos(x)) print(sin(x)) print(tan(x))
tan(x) Output[1] -06536436 [2] -0.7568025 [3]
1.157821
1. substr(x, start=n1,stop=n2) It is used to extract substrings in a character a <- "987654321" substr(a, 3, 3) Output[1]
vector. "3"
3. sub(pattern, replacement, x, It finds pattern in x and replaces it with st1<- "England is beautiful but no the part of
ignore.case =FALSE, fixed=FALSE) replacement (new) text. EU" sub("England', "UK", st1) Output[1] "UK
is beautiful but not a part of EU"
4. paste(..., sep="") It concatenates strings after using sep string to paste('one',2,'three',4,'five') Output[1] one 2
separate them. three 4 five
5. strsplit(x, split) It splits the elements of character vector x at split a<-"Split all the character" print(strsplit(a,
point. "")) Output[[1]] [1] "split" "all" "the"
"character"
6. tolower(x) It is used to convert the string into lower case. st1<- "shuBHAm" print(tolower(st1))
Output[1] shubham
7. toupper(x) It is used to convert the string into upper case. st1<- "shuBHAm" print(toupper(st1))
Output[1] SHUBHAM
20
Statistical Probability Functions
• R provides various statistical probability functions to perform statistical task. These statistical
functions are very helpful to find normal density, normal quantile and many more calculation. In
R, there are following functions which are used:
S. No Function Description Example
1. dnorm(x, m=0, sd=1, log=False) It is used to find the height of the probability a <- seq(-7, 7, by=0.1) b <- dnorm(a,
distribution at each point to a given mean and mean=2.5, sd=0.5)
standard deviation png(file="dnorm.png") plot(x,y)
dev.off()
2. pnorm(q, m=0, sd=1, it is used to find the probability of a normally a <- seq(-7, 7, by=0.2) b <- dnorm(a,
lower.tail=TRUE, log.p=FALSE) distributed random numbers which are less than the mean=2.5, sd=2)
value of a given number. png(file="pnorm.png") plot(x,y)
dev.off()
3. qnorm(p, m=0, sd=1) It is used to find a number whose cumulative value a <- seq(1, 2, by=002) b <- qnorm(a,
matches with the probability value. mean=2.5, sd=0.5)
png(file="qnorm.png") plot(x,y)
dev.off()
4. rnorm(n, m=0, sd=1) It is used to generate random numbers whose y <- rnorm(40)
distribution is normal. png(file="rnorm.png") hist(y,
main="Normal Distribution")
dev.off()
5. dbinom(x, size, prob) It is used to find the probability density distribution a<-seq(0, 40, by=1) b<- 21dbinom(a,
at each point. 40, 0.5) png(file="pnorm.png")
Statistical Probability Functions
S. No Function Description Example
6. pbinom(q, size, prob) It is used to find the cumulative probability (a single a <- pbinom(25, 40,0.5) print(a)
value representing the probability) of an event. Output[1] 0.9596548
7. qbinom(p, size, prob) It is used to find a number whose cumulative value a <- qbinom(0.25, 40,01/2) print(a)
matches the probability value. Output[1] 18
8. rbinom(n, size, prob) It is used to generate required number of random a <- rbinom(6, 140,0.4) print(a) Output[1]
values of a given probability from a given sample. 55 61 46 56 58 49
9. dpois(x, lamba) it is the probability of x successes in a period when the dpois(a=2, lambda=3)+dpois(a=3,
expected number of events is lambda (λ) lambda=3)+dpois(z=4, labda=4)
Output[1] 0.616115
10. ppois(q, lamba) It is a cumulative probability of less than or equal to q ppois(q=4, lambda=3, lower.tail=TRUE)-
successes. ppois(q=1, lambda=3, lower.tail=TRUE)
Output[1] 0.6434504
11. rpois(n, lamba) It is used to generate random numbers from the rpois(10, 10) [1] 6 10 11 3 10 7 7 8 14 12
poisson distribution.
12. dunif(x, min=0, max=1) This function provide information about the uniform dunif(x, min=0, max=1, log=FALSE)
distribution on the interval from min to max. It gives
the density.
22
Statistical Probability Functions
S. No Function Description Example
13. punif(q, min=0, max=1) It gives the distributed function punif(q, min=0, max=1, lower.tail=TRUE,
log.p=FALSE)
14. qunif(p, min=0, max=1) It gives the quantile function. qunif(p, min=0, max=1, lower.tail=TRUE,
log.p=FALSE)
15. runif(x, min=0, max=1) It generates random deviates. runif(x, min=0, max=1)
23
Other Statistical Function
S. No Function Description Example
1. mean(x, trim=0, It is used to find the mean for x object a<-c(0:10, 40) xm<-mean(a) print(xm) Output[1]
na.rm=FALSE) 7.916667
2. sd(x) It returns standard deviation of an object. a<-c(0:10, 40) xm<-sd(a) print(xm) Output[1] 10.58694
7. diff(x, lag=1) It returns differences with lag indicating which lag to a<-c(0:10, 40) xm<-diff(a) print(xm) Output[1] 1 1 1 1 1 1
use. 1 1 1 1 30
10. scale(x, center=TRUE, Column center or standardize a matrix. a <- matrix(1:9,3,3) scale(x) Output[,1] [1,] -0.747776547
scale=TRUE) [2,] -0.653320562 [3,] -0.558864577 [4,] -0.464408592
[5,] -0.369952608 [6,] -0.275496623 [7,] -0.181040638
[8,] -0.086584653 [9,] 0.007871332 [10,] 0.102327317
[11,] 0.196783302 [12,] 3.030462849
attr(,"scaled:center") [1] 7.916667 attr(,"scaled:scale") [1]
10.58694 24
Any
Queries?
Thank you