R/C2/Functions-in-R/English

From Script | Spoken-Tutorial
Jump to: navigation, search

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:
  • Need for functions
  • How to create a user-defined function
  • Scope of variables
Show Slide

Pre-requisites

https://spoken-tutorial.org/

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.

Show Slide

System Specifications

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.

Show Slide

Download Files

For this tutorial, we will use
  • A script file myFunctions.R.

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

  • 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.
Show Slide

Use-defined Functions

  • User-defined functions are specific to user’s requirements.
  • Once created these functions can be used as the built-in 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:
  • Name
  • Arguments
  • Body
  • Return value
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
  • 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.
[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:
  • Need for functions
  • How to create a user-defined function
  • Scope of variables
Show Slide

Assignment

We now suggest an assignment.
  1. Create a function which computes combination of two numbers.
  2. 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.
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.

Contributors and Content Editors

Madhurig, Nancyvarkey, Sudhakarst