Difference between revisions of "R/C2/Functions-in-R/English"
Nancyvarkey (Talk | contribs) |
|||
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: | ||
Line 24: | Line 24: | ||
|- | |- | ||
− | || | + | ||Show Slide |
− | + | ||
− | Show | + | |
Pre-requisites | Pre-requisites | ||
Line 38: | Line 36: | ||
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 | ||
Line 48: | Line 46: | ||
Install '''R''' version 3.2.0 or higher. | 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 | ||
Line 74: | Line 72: | ||
|- | |- | ||
− | || Show | + | || Show Slide |
Use-defined Functions | Use-defined Functions | ||
Line 82: | Line 80: | ||
|- | |- | ||
− | || Show | + | || Show Slide |
'''User-defined functions''' | '''User-defined functions''' | ||
Line 89: | Line 87: | ||
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 | ||
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 174: | Line 171: | ||
|| 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. | ||
Line 180: | Line 176: | ||
|| 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'''. | ||
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 | ||
Line 303: | Line 298: | ||
|- | |- | ||
|| 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 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 335: | Line 330: | ||
|| Highlight '''result <- 0''' in the '''Source''' window | || Highlight '''result <- 0''' in the '''Source''' window | ||
|| Here, the '''variable result''' is defined inside the '''function.''' | || Here, the '''variable result''' is defined inside the '''function.''' | ||
− | |||
So its scope is limited to this '''function''' only. | So its scope is limited to this '''function''' only. | ||
Line 368: | Line 362: | ||
|| Select all lines of the '''function sum_between_two.'''. | || 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 | ||
Line 393: | Line 384: | ||
|- | |- | ||
− | || Show | + | || Show Slide |
Assignment | Assignment | ||
Line 403: | Line 394: | ||
|- | |- | ||
− | || 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. |