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.

R Courses

Certification available

Introduction to R

BeginnerSkill Level
4 hr
2.6M
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

Google Cloud for Data Scientists: Harnessing Cloud Resources for Data Analysis

How can using Google Cloud make data analysis easier? We explore examples of companies that have already experienced all the benefits.

Oleh Maksymovych

9 min

40 R Programming Interview Questions & Answers For All Levels

Learn the 40 fundamental R programming interview questions and answers to them for all levels of seniority: entry-level, intermediate, and advanced questions.
Elena Kosourova's photo

Elena Kosourova

20 min

A Guide to Docker Certification: Exploring The Docker Certified Associate (DCA) Exam

Unlock your potential in Docker and data science with our comprehensive guide. Explore Docker certifications, learning paths, and practical tips.
Matt Crabtree's photo

Matt Crabtree

8 min

Bash & zsh Shell Terminal Basics Cheat Sheet

Improve your Bash & zsh Shell skills with the handy shortcuts featured in this convenient cheat sheet!
Richie Cotton's photo

Richie Cotton

6 min

Functional Programming vs Object-Oriented Programming in Data Analysis

Explore two of the most commonly used programming paradigms in data science: object-oriented programming and functional programming.
Amberle McKee's photo

Amberle McKee

15 min

A Comprehensive Introduction to Anomaly Detection

A tutorial on mastering the fundamentals of anomaly detection - the concepts, terminology, and code.
Bex Tuychiev's photo

Bex Tuychiev

14 min

See MoreSee More