any(), all()

Two other useful functions are any and all. The any function takes a vector of logicals and returns TRUE if any of the entries is TRUE. The all function takes a vector of logicals and returns TRUE if all of the entries are TRUE. Here is an example:

z <- c(TRUE, TRUE, FALSE)
any(z)
#> [1] TRUE
all(z)
#> [1] FALSE

Instruction

  • Fix the code to check whether there is a value larger than 10 or check whether there are all values larger than 10.
vec <- c(1:5, NA, 6:11, NA, 21, NA, 3:5) vec_noNA <- ifelse(is.na(vec), 0, vec) vec <- vec_noNA rm(vec_noNA) # Check the pre-defined variable 'vec'. head(vec) # Check whether there is a value larger than 10. any(vec > __) # Check whether all values are larger than 10. all(vec > __) # Create a code to check whether there exists a value larger than 10. if(________){ print("There exists a value larger than 10") } # Check the pre-defined variable 'vec'. head(vec) # Check whether there is a value larger than 10. any(vec > 10) # Check whether all values are larger than 10. all(vec > 10) # Create a code to check whether there exists a value larger than 10. if(any(vec > 10)){ print("There exists a value larger than 10") } msg <- "Please see that objects are well-defined and correct." test_function(any) test_function(all) success_msg("Great! Head over to the next exercise.")

Previous: 2-3 | ifelse() function

Next: 2-5 | Defining a function

Back to Main