
If you would like to learn more about R, you can find all of our R resources here.Ĭheck out our Using Functions in R 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.

CongratulationsĬongratulations, you have made it to the end of this tutorial! 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'.
#Rstudio if else code
The above code has 'x$Result' as a variable is used to add a new column 'Result' in a Data Frame. The above code gives the output as below: Student Marks Result Finally, both columns are combined to form data frames and store to 'x'. Another column is "Marks", which contains a vector input with the value as (35,75,45,30,85). 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"). If Student scores marks above 40, then he/she may be considered 'Pass' otherwise considered 'Fail' in an exam. The example below demonstrates the use of 'ifelse()' function along with the use of a DataFrame. Finally when the individual vector elements is TRUE gets change to 'odd' whereas the 'FALSE' will change to 'even'. 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"). The internal working of code above produces a logical vector as c(FALSE,TRUE,FALSE,TRUE,FALSE).

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' is the vector which consists of a list of numbers. Let's quickly look at an example below where the following code will check whether numbers are odd or even. b: Executes when the logical_expression is FALSE. a: Executes when the logical_expression is TRUE.ģ. logical_expression: Indicates an input vector, which in turn will return the vector of the same size as output.Ģ. The argument above in 'ifelse' states that:ġ. The syntax of 'ifelse()' function in R is done by: If the logical condition is not TRUE, apply the. All of the vector values are taken as an argument at once rather than taking individual values as an argument multiple times. Example 1: Applying if() and else() Functions in R Check whether a logical condition (i.e. Also, it uses the 'vectorized' technique, which makes the operation faster.

The 'ifelse()' function is the alternative and shorthand form of the R if-else statement.
