Difference between revisions of "R/C2/Functions-in-R/English"
Sudhakarst (Talk | contribs) |
|||
(One intermediate revision by one other user not shown) | |||
Line 9: | Line 9: | ||
|'''Narration''' | |'''Narration''' | ||
|- | |- | ||
− | || Show | + | || Show Slide |
Opening Slide | Opening Slide | ||
− | || Welcome to this tutorial on '''Functions in R | + | || Welcome to this tutorial on '''Functions in R'''. |
|- | |- | ||
|| Show slide | || Show slide | ||
− | Learning | + | Learning Objectives |
|| In this tutorial, we will learn: | || In this tutorial, we will learn: | ||
− | * Need for functions | + | * Need for '''functions''' |
− | * How to create a user-defined function | + | * How to create a '''user-defined function''' |
− | * Scope of variables | + | * Scope of '''variables''' |
|- | |- | ||
− | || | + | ||Show Slide |
− | + | ||
− | Show | + | |
Pre-requisites | Pre-requisites | ||
Line 33: | Line 31: | ||
|| To understand this tutorial, you should know, | || To understand this tutorial, you should know, | ||
* Basics of permutation and combination | * Basics of permutation and combination | ||
− | * Basic data structures | + | * Basic '''data structures''' |
− | * Conditional statements | + | * '''Conditional statements''' |
If not, please locate the relevant tutorials on '''R''' on this website. | If not, please locate the relevant tutorials on '''R''' on this website. | ||
|- | |- | ||
− | || Show | + | || Show Slide |
System Specifications | System Specifications | ||
|| This tutorial is recorded on | || This tutorial is recorded on | ||
− | * '''Ubuntu Linux '''OS version | + | * '''Ubuntu Linux '''OS version 16.04 |
− | * '''R''' version | + | * '''R''' version 3.4.4 |
− | * '''RStudio''' version | + | * '''RStudio''' version 1.1.463 |
− | Install '''R''' version | + | Install '''R''' version 3.2.0 or higher. |
|- | |- | ||
− | || Show | + | || Show Slide |
Download Files | Download Files | ||
Line 65: | Line 63: | ||
I have also set '''functions''' folder as my '''Working Directory.''' | I have also set '''functions''' folder as my '''Working Directory.''' | ||
|- | |- | ||
− | || Show | + | || Show Slide |
Functions | Functions | ||
|| | || | ||
− | * A function is a set of statements organized together to perform a specific task. | + | * A '''function''' is a set of '''statements''' organized together to perform a specific task. |
− | * R has a large number of built-in functions. | + | * '''R''' has a large number of '''built-in functions'''. |
− | * In spite of that, sometimes we need to define our own functions. | + | * In spite of that, sometimes we need to define our own '''functions'''. |
|- | |- | ||
− | || Show | + | || Show Slide |
Use-defined Functions | Use-defined Functions | ||
|| | || | ||
− | * User-defined functions are specific to user’s requirements. | + | * '''User-defined functions''' are specific to user’s requirements. |
− | * Once created these functions can be used as the built-in functions. | + | * Once created these '''functions''' can be used as the '''built-in functions'''. |
|- | |- | ||
− | || Show | + | || Show Slide |
− | User-defined functions | + | '''User-defined functions''' |
− | || An '''R function '''is created by using the | + | || An '''R function '''is created by using the '''keyword function'''. |
The syntax of an '''R function''' is as follows: | The syntax of an '''R function''' is as follows: | ||
− | ''' | + | '''myFun <- function(arguments){''' |
'''Body ''' | '''Body ''' | ||
Line 95: | Line 93: | ||
'''}''' | '''}''' | ||
|- | |- | ||
− | || Show | + | || Show Slide |
User-defined functions | User-defined functions | ||
|| The different parts of a '''function''' are: | || The different parts of a '''function''' are: | ||
* Name | * Name | ||
− | * Arguments | + | * '''Arguments''' |
− | * Body | + | * '''Body''' |
− | * Return | + | * Return value |
|- | |- | ||
Line 108: | Line 106: | ||
|| Let us switch to '''RStudio'''. | || Let us switch to '''RStudio'''. | ||
|- | |- | ||
− | || Highlight '''myFunctions.R''' in the '''Files '''window | + | || Highlight '''myFunctions.R''' in the '''Files '''window of '''RStudio ''' |
|| Open the '''script myFunctions.R '''in''' RStudio'''. | || Open the '''script myFunctions.R '''in''' RStudio'''. | ||
|- | |- | ||
|| Highlight '''sampleVec''' in the '''Source''' window | || Highlight '''sampleVec''' in the '''Source''' window | ||
− | || Here, we have declared a sample vector named '''sampleVec'''. | + | || Here, we have declared a sample '''vector''' named '''sampleVec'''. |
− | Let us find the '''summary''' of this vector by using the built-in function. | + | Let us find the '''summary''' of this '''vector''' by using the '''built-in function'''. |
|- | |- | ||
|| [RStudio] | || [RStudio] | ||
'''summary(sampleVec)''' | '''summary(sampleVec)''' | ||
− | || In the '''Source''' window, type the following command. | + | || In the '''Source''' window, type the following '''command'''. |
|- | |- | ||
|| Highlight '''Run''' button in the '''Source''' window | || Highlight '''Run''' button in the '''Source''' window | ||
− | || Save the '''script''' and run this script by clicking on the '''Source''' button. | + | || Save the '''script''' and '''run''' this script by clicking on the '''Source''' button. |
|- | |- | ||
|| Highlight the output in the '''Console''' window | || Highlight the output in the '''Console''' window | ||
|| The '''summary''' of '''sampleVec''' is displayed. | || The '''summary''' of '''sampleVec''' is displayed. | ||
− | It includes | + | It includes median, mean, etc. |
|- | |- | ||
|| Highlight '''summary''' in the '''Source''' window | || Highlight '''summary''' in the '''Source''' window | ||
− | || Similarly, '''R '''has many built-in functions to make our life easy. | + | || Similarly, '''R '''has many '''built-in functions''' to make our life easy. |
− | But we can always create a function of our own, depending | + | But we can always create a '''function''' of our own, depending on the need. |
|- | |- | ||
|| | || | ||
Line 144: | Line 142: | ||
'''}''' | '''}''' | ||
− | || In the '''Source''' window, type the following command. | + | || In the '''Source''' window, type the following '''command'''. |
|- | |- | ||
|| Highlight '''permutation''' in the '''Source''' window | || Highlight '''permutation''' in the '''Source''' window | ||
Line 150: | Line 148: | ||
|- | |- | ||
|| Highlight '''function(a,b)''' in the '''Source''' window | || Highlight '''function(a,b)''' in the '''Source''' window | ||
− | || Next, we have passed two values as arguments. | + | || Next, we have passed two values as '''arguments'''. |
|- | |- | ||
|| Highlight '''factorial(a)/factorial(a-b) '''in the Source window | || Highlight '''factorial(a)/factorial(a-b) '''in the Source window | ||
Line 156: | Line 154: | ||
|- | |- | ||
|| Highlight '''Run''' button in the '''Source''' window | || Highlight '''Run''' button in the '''Source''' window | ||
− | || Run the current line by pressing '''Ctrl+Enter''' keys simultaneously. | + | || Run the current line by pressing '''Ctrl + Enter''' keys simultaneously. |
|- | |- | ||
|| Highlight '''permutation''' in the '''Source''' window | || Highlight '''permutation''' in the '''Source''' window | ||
|| Now, let us test this '''function''' to check whether it gives correct results. | || Now, let us test this '''function''' to check whether it gives correct results. | ||
− | |||
First, we will calculate the '''permutation''' of 5 and 2. | First, we will calculate the '''permutation''' of 5 and 2. | ||
Line 170: | Line 167: | ||
|- | |- | ||
|| Highlight '''Run''' button in the '''Source''' window | || Highlight '''Run''' button in the '''Source''' window | ||
− | || Run the current line. | + | || '''Run''' the current line. |
|- | |- | ||
|| Highlight the output in the '''Console''' window | || Highlight the output in the '''Console''' window | ||
|| The required value of 20 is displayed. | || The required value of 20 is displayed. | ||
− | |||
Thus, our '''function''' has given the correct result. | Thus, our '''function''' has given the correct result. | ||
|- | |- | ||
|| Highlight '''function(a,b)''' in the '''Source''' window | || Highlight '''function(a,b)''' in the '''Source''' window | ||
− | || While creating functions, the arguments are optional. | + | || While creating '''functions''', the '''arguments''' are optional. |
− | + | ||
− | Let us create a function that does not take any arguments. | + | Let us create a '''function''' that does not take any '''arguments'''. |
|- | |- | ||
|| Cursor on the interface. | || Cursor on the interface. | ||
− | || We will create a function named as '''votingEligibility'''. | + | || We will create a '''function''' named as '''votingEligibility'''. |
|- | |- | ||
|| [RStudio] | || [RStudio] | ||
Line 204: | Line 199: | ||
'''}''' | '''}''' | ||
− | || In the '''Source''' window, type the following commands. | + | || In the '''Source''' window, type the following '''commands'''. |
|- | |- | ||
|| Highlight the if condition in the function. | || Highlight the if condition in the function. | ||
− | || This | + | || 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. | Remember the minimum age for Indian citizens to vote is 18 years. | ||
Line 214: | Line 209: | ||
|- | |- | ||
|| Highlight '''function()''' in the '''Source''' window | || Highlight '''function()''' in the '''Source''' window | ||
− | || Here, we have not passed any arguments. | + | || Here, we have not passed any '''arguments'''. |
|- | |- | ||
|| Highlight '''readline '''in the '''Source''' window | || Highlight '''readline '''in the '''Source''' window | ||
− | || '''readline''' | + | || '''readline function''' reads a line from the '''terminal''' in interactive use. |
|- | |- | ||
|| Highlight '''Run''' button in the '''Source''' window | || Highlight '''Run''' button in the '''Source''' window | ||
− | || Run this block of code to execute the | + | || '''Run''' this block of code to execute the '''function votingEligibility'''. |
|- | |- | ||
|| Highlight '''votingEligibility '''in the '''Source''' window | || Highlight '''votingEligibility '''in the '''Source''' window | ||
− | || Now, we will run this function to see whether it works. | + | || Now, we will run this '''function''' to see whether it works. |
|- | |- | ||
|| [RStudio] | || [RStudio] | ||
'''votingEligibility()''' | '''votingEligibility()''' | ||
− | || In the '''Source''' window, type the following command. | + | || In the '''Source''' window, type the following '''command'''. |
− | Please note that we are not passing any arguments inside this function. | + | Please note that we are not passing any '''arguments''' inside this '''function'''. |
|- | |- | ||
|| Highlight '''Run''' button in the '''Source''' window | || Highlight '''Run''' button in the '''Source''' window | ||
− | || Run the current line. | + | || '''Run''' the current line. |
|- | |- | ||
|| Highlight '''Please enter your age:''' in the '''Console''' window | || Highlight '''Please enter your age:''' in the '''Console''' window | ||
Line 241: | Line 236: | ||
|| We get a message, '''You can cast your vote'''. | || We get a message, '''You can cast your vote'''. | ||
|- | |- | ||
− | || Show | + | || Show Slide |
Example of a Function | Example of a Function | ||
|| Now let us say we want to create a '''function''' '''sum_between_two''' such that | || 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'''. | + | * It takes two natural numbers '''num1''' and '''num2''' as its '''arguments'''. |
* Then, it returns the sum of all numbers from '''num1''' to '''num2'''. | * Then, it returns the sum of all numbers from '''num1''' to '''num2'''. | ||
− | * For example, if we pass 2 and 6 to the | + | * 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. |
|- | |- | ||
Line 266: | Line 261: | ||
'''}''' | '''}''' | ||
− | || In the '''Source''' window, type the following command. | + | || In the '''Source''' window, type the following '''command'''. |
|- | |- | ||
|| Highlight '''sum_between_two''' in the '''Source''' window | || Highlight '''sum_between_two''' in the '''Source''' window | ||
− | || We have named our function as '''sum_between_two.''' | + | || We have named our '''function''' as '''sum_between_two.''' |
|- | |- | ||
|| Highlight '''function(num1, num2) '''in the '''Source''' window | || Highlight '''function(num1, num2) '''in the '''Source''' window | ||
− | || Also, we have specified the two | + | || Also, we have specified the two '''arguments num1 '''and '''num2. ''' |
|- | |- | ||
|| Highlight '''result <- 0 '''in the '''Source''' window | || Highlight '''result <- 0 '''in the '''Source''' window | ||
− | || Inside the function, we have initialized an object named '''result''' to store the sum. | + | || Inside the '''function''', we have initialized an object named '''result''' to store the sum. |
|- | |- | ||
|| Highlight '''for (i in num1:num2) '''in the Source window | || Highlight '''for (i in num1:num2) '''in the Source window | ||
− | || We have created a '''for''' | + | || We have created a '''for loop''' which will increment the '''result '''at each iteration. |
|- | |- | ||
|| Highlight '''Run''' button in the '''Source''' window | || Highlight '''Run''' button in the '''Source''' window | ||
− | || Run this block of code to execute the function. | + | || '''Run''' this block of code to execute the '''function'''. |
|- | |- | ||
|| Highlight '''sum_between_two '''in the Source window | || Highlight '''sum_between_two '''in the Source window | ||
− | || Now we test our | + | || Now we test our '''function sum_between_two '''by running it with two '''arguments'''. |
|- | |- | ||
|| [RStudio] | || [RStudio] | ||
'''sum_between_two(2, 6)''' | '''sum_between_two(2, 6)''' | ||
− | || In the '''Source''' window, type the following command. | + | || In the '''Source''' window, type the following '''command'''. |
|- | |- | ||
|| Highlight '''Run''' button in the '''Source''' window | || Highlight '''Run''' button in the '''Source''' window | ||
− | || Run the current line. | + | || '''Run''' the current line. |
|- | |- | ||
|| Highlight '''sum_between_two(2, 6)''' in the '''Console''' window | || Highlight '''sum_between_two(2, 6)''' in the '''Console''' window | ||
− | || The '''function''' with arguments 2 and 6 was executed, but we got nothing as output. | + | || The '''function''' with '''arguments''' 2 and 6 was executed, but we got nothing as output. |
Let us investigate what went wrong. | Let us investigate what went wrong. | ||
|- | |- | ||
|| Highlight '''sum_between_two(2, 6)''' in the '''Console''' window | || Highlight '''sum_between_two(2, 6)''' in the '''Console''' window | ||
− | || We know that our function got executed as we did not get any error after executing this line | + | || We know that our '''function''' got executed as we did not get any error after executing this line. |
|- | |- | ||
|| Highlight '''result <- result + i '''in the '''Source''' window | || Highlight '''result <- result + i '''in the '''Source''' window | ||
− | || It means that the object '''result '''got incremented. | + | || It means that the object named '''result ''' got incremented. |
|- | |- | ||
|| [RStudio] | || [RStudio] | ||
Line 310: | Line 305: | ||
|| Now, we will check the value of the '''result'''. | || Now, we will check the value of the '''result'''. | ||
− | In the '''Source''' window, type the following command. | + | In the '''Source''' window, type the following '''command'''. |
|- | |- | ||
|| Highlight '''Run''' button in the '''Source''' window | || Highlight '''Run''' button in the '''Source''' window | ||
− | || Run the current line. | + | || '''Run''' the current line. |
|- | |- | ||
|| Highlight the output in the '''Console''' window | || Highlight the output in the '''Console''' window | ||
Line 319: | Line 314: | ||
|- | |- | ||
|| Highlight the output in the '''Console''' window | || Highlight the output in the '''Console''' window | ||
− | || To understand what went wrong, we need to learn a concept named as '''Scope | + | || To understand what went wrong, we need to learn a concept named as '''Scope'''. |
|- | |- | ||
− | || Show | + | || Show Slide |
Scope of objects and variables | Scope of objects and variables | ||
− | || '''Scope '''is the term used to describe how objects and variables get defined within '''R'''. | + | || '''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. | + | 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. | + | So, if we try to access the same '''variable''' outside the '''function''', it will throw an error. |
|- | |- | ||
|| | || | ||
Line 334: | Line 329: | ||
|- | |- | ||
|| Highlight '''result <- 0''' in the '''Source''' window | || Highlight '''result <- 0''' in the '''Source''' window | ||
− | || Here, the | + | || Here, the '''variable result''' is defined inside the '''function.''' |
− | + | ||
− | So | + | So its scope is limited to this '''function''' only. |
|- | |- | ||
|| Highlight the output in the '''Console''' window | || Highlight the output in the '''Console''' window | ||
− | || Hence, when we tried to access this variable outside the '''function''', it threw an error. | + | || Hence, when we tried to access this '''variable''' outside the '''function''', it threw an error. |
|- | |- | ||
|| Highlight '''result <- 0''' in the '''Source''' window | || Highlight '''result <- 0''' in the '''Source''' window | ||
− | || For this problem, we can use '''return''' | + | || For this problem, we can use '''return function'''. |
|- | |- | ||
|| Highlight '''sum_between_two''' in the '''Source''' window | || Highlight '''sum_between_two''' in the '''Source''' window | ||
− | || Let us get back to our | + | || Let us get back to our '''function sum_between_two'''. |
|- | |- | ||
|| Highlight '''for (i in num1:num2) {''' | || Highlight '''for (i in num1:num2) {''' | ||
Line 355: | Line 349: | ||
in the '''Source''' window | in the '''Source''' window | ||
− | || Press '''Enter''' at the end of the '''for''' | + | || Press '''Enter''' at the end of the '''for loop'''. |
|- | |- | ||
|| [RStudio] | || [RStudio] | ||
'''return(result)''' | '''return(result)''' | ||
− | || Now type the following command. | + | || Now type the following '''command'''. |
|- | |- | ||
|| | || | ||
Line 366: | Line 360: | ||
|- | |- | ||
|| Highlight Run button in the Source window | || Highlight Run button in the Source window | ||
− | || Select all lines of the | + | || Select all lines of the '''function sum_between_two.'''. |
− | Now press '''Ctrl+Enter''' keys together to run the updated '''function'''. | + | Now press '''Ctrl + Enter''' keys together to run the updated '''function'''. |
|- | |- | ||
|| Highlight '''sum_between_two(2, 6)''' in the '''Source''' window | || Highlight '''sum_between_two(2, 6)''' in the '''Source''' window | ||
− | || Let us run the '''function''' again with arguments 2 and 6. | + | || Let us run the '''function''' again with '''arguments''' 2 and 6. |
− | + | ||
For this, we will run this line. | For this, we will run this line. | ||
Line 382: | Line 375: | ||
|| Let us summarize what we have learnt. | || Let us summarize what we have learnt. | ||
|- | |- | ||
− | || | + | ||Show Slide |
− | + | ||
− | Show | + | |
Summary | Summary | ||
|| In this tutorial, we have learnt: | || In this tutorial, we have learnt: | ||
− | * Need for functions | + | * Need for '''functions''' |
− | * How to create a user-defined function | + | * How to create a '''user-defined function''' |
− | * Scope of variables | + | * Scope of '''variables''' |
|- | |- | ||
− | || Show | + | || Show Slide |
Assignment | Assignment | ||
|| We now suggest an assignment. | || We now suggest an assignment. | ||
− | # Create a function which computes combination of two numbers. | + | # Create a '''function''' which computes combination of two numbers. |
− | # Create a function which | + | # Create a '''function''' which |
− | #* takes a natural number as an argument, and prints '''Fibonacci '''series | + | #* 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. | #* For example, consider '''fibonacci(5). '''It should print the first 5 elements of '''Fibonacci '''series, i.e. 1, 1, 2, 3, 5. | ||
|- | |- | ||
− | || Show | + | || Show Slide |
About the Spoken Tutorial Project | About the Spoken Tutorial Project | ||
Line 410: | Line 401: | ||
Please download and watch it. | Please download and watch it. | ||
|- | |- | ||
− | || Show | + | || Show Slide |
Spoken Tutorial Workshops | Spoken Tutorial Workshops |
Latest revision as of 23:20, 25 September 2019
Title of the script: Functions in R
Author: Varshit Dubey (CoE Pune) and Sudhakar Kumar (IIT Bombay)
Keywords: R, RStudio, functions, user-defined function, video tutorial
Visual Cue | Narration |
Show Slide
Opening Slide |
Welcome to this tutorial on Functions in R. |
Show slide
Learning Objectives |
In this tutorial, we will learn:
|
Show Slide
Pre-requisites |
To understand this tutorial, you should know,
If not, please locate the relevant tutorials on R on this website. |
Show Slide
System Specifications |
This tutorial is recorded on
Install R version 3.2.0 or higher. |
Show Slide
Download Files |
For this tutorial, we will use
Please download this file from the Code files link of this tutorial. |
[Computer screen]
Highlight moviesData.csv and myFunctions.R in the folder functions |
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. |
Show Slide
Functions |
|
Show Slide
Use-defined Functions |
|
Show Slide
User-defined functions |
An R function is created by using the keyword function.
The syntax of an R function is as follows: myFun <- function(arguments){ Body } |
Show Slide
User-defined functions |
The different parts of a function are:
|
Let us switch to RStudio. | |
Highlight myFunctions.R in the Files window of RStudio | Open the script myFunctions.R in RStudio. |
Highlight sampleVec in the Source window | Here, we have declared a sample vector named sampleVec.
Let us find the summary of this vector by using the built-in function. |
[RStudio]
summary(sampleVec) |
In the Source window, type the following command. |
Highlight Run button in the Source window | Save the script and run this script by clicking on the Source button. |
Highlight the output in the Console window | The summary of sampleVec is displayed.
It includes median, mean, etc. |
Highlight summary in the Source window | 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. | |
[RStudio]
permutation <- function(a,b){ factorial(a)/factorial(a-b) } |
In the Source window, type the following command. |
Highlight permutation in the Source window | Here, we have named our function as permutation. |
Highlight function(a,b) in the Source window | Next, we have passed two values as arguments. |
Highlight factorial(a)/factorial(a-b) in the Source window | Inside the function, the definition of permutation has been written. |
Highlight Run button in the Source window | Run the current line by pressing Ctrl + Enter keys simultaneously. |
Highlight permutation in the Source window | Now, let us test this function to check whether it gives correct results.
First, we will calculate the permutation of 5 and 2. |
[RStudio]
permutation(5,2) |
In the Source window, type permutation and in parentheses 5 comma 2. |
Highlight Run button in the Source window | Run the current line. |
Highlight the output in the Console window | The required value of 20 is displayed.
Thus, our function has given the correct result. |
Highlight function(a,b) in the Source window | While creating functions, the arguments are optional.
Let us create a function that does not take any arguments. |
Cursor on the interface. | We will create a function named as votingEligibility. |
[RStudio]
votingEligibility <- function(){ age <- as.integer(readline("Please enter your age: ")) if(age < 18){ print("Sorry, you cannot cast your vote.") } else{ print("Congrats! You can cast your vote.") } } |
In the Source window, type the following commands. |
Highlight the if condition in the function. | 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. |
Highlight function() in the Source window | Here, we have not passed any arguments. |
Highlight readline in the Source window | readline function reads a line from the terminal in interactive use. |
Highlight Run button in the Source window | Run this block of code to execute the function votingEligibility. |
Highlight votingEligibility in the Source window | Now, we will run this function to see whether it works. |
[RStudio]
votingEligibility() |
In the Source window, type the following command.
Please note that we are not passing any arguments inside this function. |
Highlight Run button in the Source window | Run the current line. |
Highlight Please enter your age: in the Console window | We are asked to enter our age. Let us type 21 and press Enter. |
Highlight the output in the Console window | We get a message, You can cast your vote. |
Show Slide
Example of a Function |
Now let us say we want to create a function sum_between_two such that
|
Let us switch back to RStudio. | |
[RStudio]
sum_between_two <- function(num1, num2){ result <- 0 for (i in num1:num2) { result <- result + i } } |
In the Source window, type the following command. |
Highlight sum_between_two in the Source window | We have named our function as sum_between_two. |
Highlight function(num1, num2) in the Source window | Also, we have specified the two arguments num1 and num2. |
Highlight result <- 0 in the Source window | Inside the function, we have initialized an object named result to store the sum. |
Highlight for (i in num1:num2) in the Source window | We have created a for loop which will increment the result at each iteration. |
Highlight Run button in the Source window | Run this block of code to execute the function. |
Highlight sum_between_two in the Source window | Now we test our function sum_between_two by running it with two arguments. |
[RStudio]
sum_between_two(2, 6) |
In the Source window, type the following command. |
Highlight Run button in the Source window | Run the current line. |
Highlight sum_between_two(2, 6) in the Console window | The function with arguments 2 and 6 was executed, but we got nothing as output.
Let us investigate what went wrong. |
Highlight sum_between_two(2, 6) in the Console window | We know that our function got executed as we did not get any error after executing this line. |
Highlight result <- result + i in the Source window | It means that the object named result got incremented. |
[RStudio]
print(result) |
Now, we will check the value of the result.
In the Source window, type the following command. |
Highlight Run button in the Source window | Run the current line. |
Highlight the output in the Console window | It shows, Error in print(result) : object 'result' not found. |
Highlight the output in the Console window | To understand what went wrong, we need to learn a concept named as Scope. |
Show Slide
Scope of objects and variables |
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. | |
Highlight result <- 0 in the Source window | Here, the variable result is defined inside the function.
So its scope is limited to this function only. |
Highlight the output in the Console window | Hence, when we tried to access this variable outside the function, it threw an error. |
Highlight result <- 0 in the Source window | For this problem, we can use return function. |
Highlight sum_between_two in the Source window | Let us get back to our function sum_between_two. |
Highlight for (i in num1:num2) {
result <- result + i } in the Source window |
Press Enter at the end of the for loop. |
[RStudio]
return(result) |
Now type the following command. |
I will resize the Console window. | |
Highlight Run button in the Source window | Select all lines of the function sum_between_two..
Now press Ctrl + Enter keys together to run the updated function. |
Highlight sum_between_two(2, 6) in the Source window | Let us run the function again with arguments 2 and 6.
For this, we will run this line. |
Highlight the output in the Console window | We see the output 20 as expected. |
Let us summarize what we have learnt. | |
Show Slide
Summary |
In this tutorial, we have learnt:
|
Show Slide
Assignment |
We now suggest an assignment.
|
Show Slide
About the Spoken Tutorial Project |
The video at the following link summarises the Spoken Tutorial project.
Please download and watch it. |
Show Slide
Spoken Tutorial Workshops |
We conduct workshops using Spoken Tutorials and give certificates.
Please contact us. |
Show Slide
Forum to answer questions |
Please post your timed queries in this forum. |
Show Slide
Forum to answer questions |
Please post your general queries in this forum. |
Show Slide
Textbook Companion |
The FOSSEE team coordinates the TBC project.
For more details, please visit these sites. |
Show Slide
Acknowledgment |
The Spoken Tutorial project is funded by NMEICT, MHRD, Govt. of India |
Show Slide
Thank You |
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. |