Difference between revisions of "R/C2/Functions-in-R/English"
Sudhakarst (Talk | contribs) (Created page with "'''Title of the script''': Functions in R '''Author''': Varshit Dubey (CoE Pune) and Sudhakar Kumar (IIT Bombay) '''Keywords''': R, RStudio, functions, user-defined function...") |
Sudhakarst (Talk | contribs) |
||
Line 4: | Line 4: | ||
'''Keywords''': R, RStudio, functions, user-defined function, video tutorial | '''Keywords''': R, RStudio, functions, user-defined function, video tutorial | ||
− | |||
{| border =1 | {| border =1 | ||
− | |'''Visual | + | |'''Visual Cue''' |
− | |''' | + | |'''Narration''' |
|- | |- | ||
|| Show slide | || Show slide | ||
Line 18: | Line 17: | ||
Learning Objective | Learning Objective | ||
− | |||
− | |||
|| In this tutorial, we will learn: | || In this tutorial, we will learn: | ||
Line 25: | Line 22: | ||
* How to create a user-defined function | * How to create a user-defined function | ||
* Scope of variables | * Scope of variables | ||
− | |||
|- | |- | ||
|| | || | ||
− | |||
Show slide | Show slide | ||
Line 50: | Line 45: | ||
* '''R''' version '''3.4.4''' | * '''R''' version '''3.4.4''' | ||
* '''RStudio''' version '''1.1.463''' | * '''RStudio''' version '''1.1.463''' | ||
− | |||
− | |||
Install '''R''' version '''3.2.0''' or higher. | Install '''R''' version '''3.2.0''' or higher. | ||
Line 60: | Line 53: | ||
|| For this tutorial, we will use | || For this tutorial, we will use | ||
* A '''script''' file '''myFunctions.R'''. | * A '''script''' file '''myFunctions.R'''. | ||
− | |||
− | |||
Please download this file from the '''Code files''' link of this tutorial. | Please download this file from the '''Code files''' link of this tutorial. | ||
Line 69: | Line 60: | ||
Highlight '''moviesData.csv '''and''' myFunctions.R '''in the folder '''functions''' | Highlight '''moviesData.csv '''and''' myFunctions.R '''in the folder '''functions''' | ||
|| I have downloaded and moved this file to '''functions''' folder. | || I have downloaded and moved this file to '''functions''' folder. | ||
− | |||
This folder is located in '''myProject''' folder on my '''Desktop'''. | This folder is located in '''myProject''' folder on my '''Desktop'''. | ||
− | |||
I have also set '''functions''' folder as my '''Working Directory.''' | I have also set '''functions''' folder as my '''Working Directory.''' | ||
Line 79: | Line 68: | ||
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. | ||
− | |||
|- | |- | ||
Line 88: | Line 77: | ||
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. | ||
− | |||
|- | |- | ||
Line 142: | Line 131: | ||
| | 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 upon the need. | But we can always create a function of our own, depending upon the need. | ||
|- | |- | ||
− | | | + | || |
− | | | + | || We will create a '''function''' that computes the '''permutation''' of two numbers. |
|- | |- | ||
− | | | + | || [RStudio] |
'''permutation <- function(a,b){''' | '''permutation <- function(a,b){''' | ||
Line 156: | Line 144: | ||
'''}''' | '''}''' | ||
− | | | + | || 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. | First, we will calculate the '''permutation''' of 5 and 2. | ||
|- | |- | ||
− | | | + | || [RStudio] |
'''permutation(5,2)''' | '''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 | || Highlight the output in the '''Console''' window | ||
Line 217: | Line 205: | ||
'''}''' | '''}''' | ||
|| 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 function''' '''should print a message whether an Indian citizen is eligible to vote or not. | || 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 236: | Line 219: | ||
|| '''readline''' function reads a line from the terminal in interactive use. | || '''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()''' | '''votingEligibility()''' | ||
− | | | + | || 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 |
− | | | + | || 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 | Example of a Function | ||
− | | | + | || 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 function '''sum_between_two''', it should return the value of 2 + 3 + 4 + 5 + 6. | * 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'''. |
|- | |- | ||
− | | | + | || [RStudio] |
'''sum_between_two <- function(num1, num2){''' | '''sum_between_two <- function(num1, num2){''' | ||
Line 285: | Line 266: | ||
'''}''' | '''}''' | ||
− | | | + | || 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)''' | '''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. | 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 '''result '''got incremented. |
|- | |- | ||
− | | | + | || [RStudio] |
'''print(result)''' | '''print(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 |
− | | | + | || Run the current line. |
|- | |- | ||
|| Highlight the output in the '''Console''' window | || Highlight the output in the '''Console''' window |
Revision as of 15:38, 17 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 Objective |
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: myFunc <- 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 upon 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.
|
[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.
|
Highlight function(a,b) in the Source window | While creating functions, the arguments are optional.
|
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.
|
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 result got incremented. |
[RStudio]
print(result) |
Now, we will check the value of the result.
|
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.
|
Let us switch to RStudio. | |
Highlight result <- 0 in the Source window | Here, the variable result is defined inside the function.
|
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.
|
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.# Create a function which computes combination of two numbers.
|
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.
|
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).
|