Skip to main content
HomeAbout RLearn R

IF ELSE Function in R

Learn in detail about the ifelse() function, including syntax, along with finding whether a number is odd or even, and finally, with an example to see whether a student passed or failed their exam.
Jun 2020  · 4 min read
banner

The 'ifelse()' function is the alternative and shorthand form of the R if-else statement. Also, it uses the 'vectorized' technique, which makes the operation faster. All of the vector values are taken as an argument at once rather than taking individual values as an argument multiple times.

Syntax

The syntax of 'ifelse()' function in R is done by:
ifelse(logical_expression, a , b)

The argument above in 'ifelse' states that:
1.logical_expression: Indicates an input vector, which in turn will return the vector of the same size as output.
2. a: Executes when the logical_expression is TRUE.
3. b: Executes when the logical_expression is FALSE.

Example (Odd or Even)

Let's quickly look at an example below where the following code will check whether numbers are odd or even. 'v' is the vector which consists of a list of numbers. In 'ifelse' function the expression 'v%%2==1' checks the remainder of each number in the 'v' to be one and happens to be TRUE will print "odd" otherwise in FALSE will print "even".

v = c(14,7,6,9,2)
ifelse(v %% 2 == 1,"odd","even")
  1. 'even'
  2. 'odd'
  3. 'even'
  4. 'odd'
  5. 'even'

The above code gives the output as:
'even' 'odd' 'even' 'odd' 'even'
The internal working of code above produces a logical vector as c(FALSE,TRUE,FALSE,TRUE,FALSE). The first parameter will form a string vector of c("odd","odd","odd","odd","odd") also the second parameter which in turn will produce string vector as c("even',"even","even","even","even"). Finally when the individual vector elements is TRUE gets change to 'odd' whereas the 'FALSE' will change to 'even'.

Example (Pass or Fail)

The example below demonstrates the use of 'ifelse()' function along with the use of a DataFrame. If Student scores marks above 40, then he/she may be considered 'Pass' otherwise considered 'Fail' in an exam.

Let's quickly create a Data Frame where there is a name of a student as "Student" column with vector as input containing ("Ron", "Jake", "Ava", "Sophia", "Mia"). Another column is "Marks", which contains a vector input with the value as (35,75,45,30,85). Finally, both columns are combined to form data frames and store to 'x'.

x <- data.frame("Student" = c("Ron","Jake","Ava","Sophia","Mia"),"Marks" = c(35,75,45,30,85))
str(x)
'data.frame':    5 obs. of  2 variables:
 $ Student: Factor w/ 5 levels "Ava","Jake","Mia",..: 4 2 1 5 3
 $ Marks  : num  35 75 45 30 85
'data.frame':    5 obs. of  2 variables:
 $ Student: Factor w/ 5 levels "Ava","Jake","Mia",..: 4 2 1 5 3
 $ Marks  : num  35 75 45 30 85

The above code shows the structure of a Data Frame using the 'str(x)' where it says there are 5 observations with 2 variables with the respective values of Student and Marks printed out.

x$Result = ifelse(x$"Marks">40,"Pass","Fail")
print(x)

The above code gives the output as below:

    Student Marks Result
1    Ron    35   Fail
2   Jake    75   Pass
3    Ava    45   Pass
4 Sophia    30   Fail
5    Mia    85   Pass 

The above code has 'x$Result' as a variable is used to add a new column 'Result' in a Data Frame. The 'ifelse()' function has an expression as 'x$"Marks">40', which checks the vector values from Marks and decides the 'Result' to be 'Pass' when Marks is greater than 40 otherwise the 'Result' is 'Fail'.

Congratulations

Congratulations, you have made it to the end of this tutorial!

You've learned about R's ifelse() function with is syntax along with it's help in finding whether a number is Odd or Even and finally with its example to see whether a student is Pass or Fail in an exam.

If you would like to learn more about R, you can find all of our R resources here.

Check out our Using Functions in R tutorial.

Topics

R Courses

Course

Introduction to R

4 hr
2.7M
Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Data Science in Finance: Unlocking New Potentials in Financial Markets

Discover the role of data science in finance, shaping tomorrow's financial strategies. Gain insights into advanced analytics and investment trends.

Shawn Plummer

9 min

5 Common Data Science Challenges and Effective Solutions

Emerging technologies are changing the data science world, bringing new data science challenges to businesses. Here are 5 data science challenges and solutions.
DataCamp Team's photo

DataCamp Team

8 min

Navigating R Certifications in 2024: A Comprehensive Guide

Explore DataCamp's R programming certifications with our guide. Learn about Data Scientist and Data Analyst paths, preparation tips, and career advancement.
Matt Crabtree's photo

Matt Crabtree

8 min

A Data Science Roadmap for 2024

Do you want to start or grow in the field of data science? This data science roadmap helps you understand and get started in the data science landscape.
Mark Graus's photo

Mark Graus

10 min

R Markdown Tutorial for Beginners

Learn what R Markdown is, what it's used for, how to install it, what capacities it provides for working with code, text, and plots, what syntax it uses, what output formats it supports, and how to render and publish R Markdown documents.
Elena Kosourova 's photo

Elena Kosourova

12 min

Introduction to DynamoDB: Mastering NoSQL Database with Node.js | A Beginner's Tutorial

Learn to master DynamoDB with Node.js in this beginner's guide. Explore table creation, CRUD operations, and scalability in AWS's NoSQL database.
Gary Alway's photo

Gary Alway

11 min

See MoreSee More