ifelse() function

A related function that is very useful is ifelse. This function takes three arguments: a logical and two possible answers. If the logical is TRUE, the value in the second argument is returned and if FALSE, the value in the third argument is returned. Here is an example:

a <- 0
ifelse(a > 0, 1/a, NA)
#> [1] NA

The function is particularly useful because it works on vectors. It examines each entry of the logical vector and returns elements from the vector provided in the second argument, if the entry is TRUE, or elements from the vector provided in the third argument, if the entry is FALSE.

a <- c(0,1,2,-4,5)
result <- ifelse(a > 0, 1/a, NA)

This table helps us see what happened:

a is_a_positive answer1 answer2 result
0 FALSE Inf NA NA
1 TRUE 1.00 NA 1.0
2 TRUE 0.50 NA 0.5
-4 FALSE -0.25 NA NA
5 TRUE 0.20 NA 0.2

Instruction

vec <- c(1:5, NA, 6:11, NA, 21, NA, 3:5) # Check the pre-defined variable 'vec'. head(vec) # Find the total number of NA in vec. sum(is.na(vec)) # when a value in vec is NA, change NA to 0 and save it into vec_noNA. vec_noNA <- ifelse(is.na(vec), ,) # Find the total number of NA in vec_noNA sum(is.na(vec_noNA)) # Check the pre-defined variable 'vec'. head(vec) # Find the total number of NA in vec. sum(is.na(vec)) # when a value in vec is NA, change NA to 0 and save it into vec_noNA. vec_noNA <- ifelse(is.na(vec), 0, vec) # Find the total number of NA in vec_noNA sum(is.na(vec_noNA)) msg <- "Please see that objects are well-defined and correct." test_object(vec_noNA, incorrect_msg = msg, undefined_msg = msg) success_msg("Great! Head over to the next exercise.")

Previous: 2-2 | Conditional Expression

Next: 2-4 | any(), all()

Back to Main