R/C2/Conditional-Statements/English

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

Title of the script: Conditional Statements

Author: Varshit Dubey (CoE Pune) and Sudhakar Kumar (IIT Bombay)

Keywords: R, RStudio, conditional, if, else, else if, video tutorial

Visual Cue Narration
Show slide

Opening Slide

Welcome to this tutorial on Conditional Statements.
Show slide

Learning Objective

In this tutorial, we will learn about,
  • Conditional statements
  • if, else, and else if statements
Show slide

Pre-requisites

https://spoken-tutorial.org/

To understand this tutorial, you should know,
  • Basic data structures
  • Indexing and slicing data frames

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 data frame moviesData.csv
  • A script file conditionalStats.R.

Please download these files from the Code files link of this tutorial.

[Computer screen]

Highlight moviesData.csv and conditionalStats.R in the folder conditionalStatements

I have downloaded and moved these files to conditionalStatements folder.

This folder is located in myProject folder on my Desktop.

I have also set conditionalStatements folder as my Working Directory.

Show slide

Conditional Statements

  • Conditional statements are used to execute some logical conditions in the code.
  • if, else and else if are the basic conditional statements.
Let us switch to RStudio.
Highlight conditionalStats.R in the Files window of RStudio Open the script conditionalStats.R in RStudio.
Highlight inScore in the Source window Here, we have declared a vector inScore.

The elements of this vector represent the runs scored by India in three different one-day matches.

Highlight ausScore in the Source window Similarly, we have declared another vector ausScore.

The elements of this vector represent the runs scored by Australia in three different one-day matches.

Highlight the Source button Run this script by clicking on the Source button.
Highlight movies in the Source window movies data frame opens in the Source window.

This data frame will be used later in this tutorial.

Highlight the script conditionalStats.R in the Source window Click on the script conditionalStats.R
Highlight inScore and ausScore in the Source window Let us now find which country has won the first one day match.
[RStudio]

if(inScore[1] > ausScore[1]){

print("India won the first ODI!")

}

In the Source window, type the following command.
Highlight if in the Source window It means that if the condition is TRUE then execute the expression inside the curly brackets.
Highlight Run button in the Source window Save the script and run the current line by pressing Ctrl+Enter keys simultaneously.
I will resize the Console window.
Highlight the output in the Console window As India scored more runs than Australia in the first one day match, the message, India won the first ODI!, is displayed.
Highlight inScore and ausScore in the Source window Let us now find which country won the second one day match.
I will resize the Console window.
[RStudio]

if (inScore[2] > ausScore[2]){

print("India won the second ODI!")

}

In the Source window, type the following command.
Highlight Run button in the Source window Save the script and run the current line.
Highlight inScore and ausScore in the Source window.

Highlight the output in the Console window

As Australia scored more runs than India in the second one day match, we should get a message, Australia won the second ODI!.

But no message is displayed on the Console.

Highlight the last if statement in the Source window Here the if statement will be executed only when India scores more runs than Australia in the second one day match.

Hence, we need to add an else statement with another expression.

This expression should be executed when the if condition is not satisfied.

Highlight the last if statement in the Source window Click on the last line of the if statement.
[RStudio]

else{

print("Australia won the second ODI!")

}

Now, type the following command.

Please note that the else statement begins on the same line where if statement ends.

Highlight Run button in the Source window Save the script and run the current line.
I will resize the Console window.
Highlight the output in the Console window Now, we get a message, Australia won the second ODI!
Highlight the if-else statement in Source window There is another efficient way to write this if-else statement.
[RStudio]

ifelse (inScore[2] > ausScore[2],

"India won the second ODI!",

"Australia won the second ODI!")

In the Source window, type the following command.
Highlight ifelse in the Source window Here, we are using ifelse for comparing the elements of two different vectors.
Highlight ifelse in the Source window

Highlight inScore[2] > ausScore[2] in the Source window

Here the ifelse statement has three arguments.
  • test - It is an object which can be forced to a logical mode.

Here test is for the comparison of scores.

Highlight India won the second ODI! in the Source window
  • yes - It returns values for true elements of the test.

Here, the first statement represents the value of the true element.

Highlight Australia won the second ODI! in the Source window
  • no - It returns values for false elements of the test

The second statement represents the value of the false element.

Highlight Run button in the Source window Save the script and run the current line.
Highlight the output in the Console window We get the same message, Australia won the second ODI!

In the Source window, scroll up to locate the two vectors.

Highlight inScore and ausScore in the Source window In the third one day match, India and Australia have scored the same number of runs.

Let us use an ifelse logic to find out the winner in this case.

[RStudio]

if (inScore[3] > ausScore[3]){

print("India won the third ODI!")

} else{

print("Australia won the third ODI!")

}

In the Source window, click on the next line after the ifelse statement.

Now type the following command.

Highlight Run button in the Source window Save the script and run the current line.
Highlight the output in the Console window We get the message, Australia won the third ODI! This is not correct.
Highlight the if-else statement in the Source window So, we need to modify our logic.
[RStudio]

if (inScore[3] > ausScore[3]){

print("India won the third ODI!")

} else if (inScore[3] == ausScore[3]){

print("Third ODI was a tie.")

} else {

print("Australia won the third ODI!")

}

In the Source window, type the following command.


Please note that else if statement begins on the same line where if statement ends.

Highlight Run button in the Source window Run the current line.
I will resize the Console window.
Highlight the output in the Console window Now, we got the correct message, Third ODI was a tie.
I will resize the Console window again.
Highlight the last if-else statement in the Source window A conditional structure contains only one if statement.

It may contain as many else if statements as you need and only one else statement.

The else statement will be executed only when all the above if and else if statements are FALSE.

Highlight ifelse statement in the Source window In the Source window, scroll up.

Here, we have used ifelse for comparing the elements of two different vectors.

Highlight ifelse in the Source window Now, we will learn how to use ifelse statements for comparing the two columns of a data frame.
Highlight movies in the Source window In the Source window, scroll down to locate the last ifelse statement.

In the Source window, click on movies data frame.

Highlight the scroll bar in the Source window In the Source window, scroll from left to right.

This will enable us to see the remaining objects of movies data frame.

Highlight audience_score and critics_score in movies Let us compare the critics_score and audience_score.
Show slide

Example

We will add a new column named dev in the movies data frame, which will show
  • 1, if audience_score is greater than critics_score and
  • 0, otherwise.
Highlight the script conditionalStats.R in the Source window Click on the script conditionalStats.R
[RStudio]

movies$dev <- ifelse(movies$audience_score > movies$critics_score, 1, 0)

View(movies)

In the Source window, type the following command.
Highlight Run button in the Source window Save the script and run the last two lines.
Highlight movies in the Source window movies data frame opens in the Source window.
Highlight the scroll bar in the Source window In the Source window, scroll from left to right.
Highlight dev in movies A new column named dev has been added. It has 1 or 0.

Remember, 1 means audience_score is greater than critics_score.

Show slide

Example

  • Now, we will find the number of movies, in which audience_score is greater than critics_score.
  • For this, we will use the sum function along with the if condition.
Highlight the script conditionalStats.R in the Source window Click on the script conditionalStats.R
[RStudio]

sum(ifelse(movies$audience_score > movies$critics_score, 1, 0))

In the Source window, type the following command.
Highlight Run button in the Source window Save the script and run the current line.
Highlight the output in the Console window So, there are 312 movies, in which audience_score is greater than critics_score.
Let us summarize what we have learnt.
Show slide

Summary

In this tutorial, we have learnt about,
  • Conditional statements
  • if, else, and else if statements
Show slide

Assignment

We now suggest an assignment.
  • Use the built-in data set iris. Find the species, in which Sepal.Length is greater than Petal.Length
  • Count all such species.
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

Nancyvarkey, Sudhakarst