Site icon R-bloggers

R ifelse() Function

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In R, the ifelse() function is a shorthand vectorized alternative to the standard if...else statement.

Most of the functions in R take a vector as input and return a vectorized output. Similarly, the vector equivalent of the traditional if...else block is the ifelse() function.

The syntax of the ifelse() function is:

ifelse(test_expression, x, y)

The output vector has the element x if the output of the test_expression is TRUE. If the output is FALSE, then the element in the output vector will be y.


Example 1: ifelse() Function for Odd/Even Numbers

# input vector
x <- c(12, 9, 23, 14, 20, 1, 5)

# ifelse() function to determine odd/even numbers
ifelse(x %% 2 == 0, "EVEN", "ODD")

Output

[1] "EVEN" "ODD"  "ODD"  "EVEN" "EVEN" "ODD"  "ODD" 

In this program, we have defined a vector x using the c() function in R. The vector contains a few odd and even numbers.

We then used the ifelse() function which takes the vector x as an input. A logical operation is then performed on x to determine if the elements are odd or even.

For each element in the vector, if the test_expression evaluates to TRUE, then the corresponding output element is “EVEN“, else it’s “ODD“.


Example 2: ifelse() Function for Pass/Fail

# input vector of marks
marks <- c(63, 58, 12, 99, 49, 39, 41, 2)

# ifelse() function to determine pass/fail
ifelse(marks < 40, "FAIL", "PASS")

Output

[1] "PASS" "PASS" "FAIL" "PASS" "PASS" "FAIL" "PASS" "FAIL"

This program determines if the students have passed or failed based on a condition. Here, if the marks in the vector are less than 40, then the student is considered to have failed.

To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.