Welcome to this tutorial on Functions in R
In this tutorial, we will learn: Need for functions
How to create a user-defined function
Scope of variables
To understand this tutorial, you should know,
Basics of permutation and combination
Basic data structures
Conditional statements
If not, please locate the relevant tutorials on R on this website.
This tutorial is recorded on Ubuntu Linux OS version 16.04
R version 3.4.4
RStudio version 1.1.463
Install R version 3.2.0 or higher.
For this tutorial, we will use
A script file myFunctions.R.
Please download this file from the Code files link of this tutorial.
I have downloaded and moved this file to functions folder.
This folder is located in myProject folder on my Desktop.
I have also set functions folder as my Working Directory.
A function is a set of statements organized together to perform a specific task.
R has a large number of built-in functions.
In spite of that, sometimes we need to define our own functions.
User-defined functions are specific to user’s requirements.
Once created these functions can be used as the built-in functions.
An R function is created by using the keyword function.
The syntax of an R function is as follows:
The different parts of a function are: Name, Arguments, Body, Return value.
Let us switch to RStudio.
Open the script myFunctions.R in RStudio.
Here, we have declared a sample vector named sampleVec.
Let us find the summary of this vector by using the built-in function.
In the Source window, type the following command.
Save the script and run this script by clicking on the Source button.
The summary of sampleVec is displayed.
It includes median, mean, etc.
Similarly, R has many built-in functions to make our life easy.
But we can always create a function of our own, depending on the need.
We will create a function that computes the permutation of two numbers.
In the Source window, type the following command.
Here, we have named our function as permutation.
Next, we have passed two values as arguments.
Inside the function, the definition of permutation has been written.
Run the current line by pressing Ctrl + Enter keys simultaneously.
Now, let us test this function to check whether it gives correct results.
First, we will calculate the permutation of 5 and 2.
In the Source window, type permutation and in parentheses 5 comma 2.
Run the current line.
The required value of 20 is displayed.
Thus, our function has given the correct result.
While creating functions, the arguments are optional.
Let us create a function that does not take any arguments.
We will create a function named as votingEligibility.
In the Source window, type the following commands.
This function should print a message whether an Indian citizen is eligible to vote or not.
Remember the minimum age for Indian citizens to vote is 18 years.
Here, we have not passed any arguments.
readline function reads a line from the terminal in interactive use.
Run this block of code to execute the function votingEligibility.
Now, we will run this function to see whether it works.
In the Source window, type the following command.
Please note that we are not passing any arguments inside this function.
Run the current line.
We are asked to enter our age.
Let us type 21 and press Enter.
We get a message, You can cast your vote.
Now let us say we want to create a function sum_between_two such that
it takes two natural numbers num1 and num2 as its arguments.
Then, it returns the sum of all numbers from num1 to num2.
For example, if we pass 2 and 6 to the function sum_between_two,
it should return the value of 2 + 3 + 4 + 5 + 6.
Let us switch back to RStudio.
In the Source window, type the following command.
We have named our function as sum_between_two.
Also, we have specified the two arguments num1 and num2.
Inside the function, we have initialized an object named result to store the sum.
We have created a for loop which will increment the result at each iteration.
Run this block of code to execute the function.
Now we test our function sum_between_two by running it with two arguments.
In the Source window, type the following command.
Run the current line.
The function with arguments 2 and 6 was executed, but we got nothing as output.
Let us investigate what went wrong.
We know that our function got executed as we did not get any error after executing this line.
It means that the object named result got incremented.
Now, we will check the value of the result.
In the Source window, type the following command.
Run the current line.
It shows, Error in print(result) : object 'result' not found.
To understand what went wrong, we need to learn a concept named as Scope.
Scope is the term used to describe how objects and variables get defined within R.
If a variable is defined inside a function, then it can be accessed inside the function only.
So, if we try to access the same variable outside the function, it will throw an error.
Let us switch to RStudio.
Here, the variable result is defined inside the function.
So its scope is limited to this function only.
Hence, when we tried to access this variable outside the function, it threw an error.
For this problem, we can use return function.
Let us get back to our function sum_between_two.
Press Enter at the end of for loop.
Now type the following command.
I will resize the Console window.
Select all lines of the function sum_between_two..
Now press Ctrl + Enter keys together to run the updated function.
Let us run the function again with arguments 2 and 6.
For this, we will run this line.
We see the output 20 as expected.
Let us summarize what we have learnt.
In this tutorial, we have learnt: Need for functions
How to create a user-defined function
Scope of variables
We now suggest an assignment.
Create a function which computes combination of the two numbers.
Create a function which takes a natural number as an argument, and prints Fibonacci series
For example, consider fibonacci(5). It should print the first 5 elements of Fibonacci series, i.e. 1, 1, 2, 3, 5.
The video at the following link summarises the Spoken Tutorial project.
Please download and watch it.
We conduct workshops using Spoken Tutorials and give certificates.
Please contact us.
Please post your timed queries in this forum.
Please post your general queries in this forum.
The FOSSEE team coordinates the TBC project.
For more details, please visit these sites.
The Spoken Tutorial project is funded by NMEICT, MHRD, Govt. of India
The script for this tutorial was contributed by Varshit Dubey (College of Engineering Pune).
This is Sudhakar Kumar from IIT Bombay signing off.
Thanks for watching.