The goal of this tutorial is to learn how to simplify our code by using the all and any functions.
# Let's use the iris dataset
data(iris)
# We want to know if there is any value of Petal.Length bigger than 6
if(length(which(iris$Petal.Length > 6)) > 0) print("There is")
## [1] "There is"
# We will check now if there are entries of the versicolor family
if(length(which(iris$Species == "versicolor"))) print("Versicolour")
## [1] "Versicolour"
# Now we want to know if all the plants in iris are versicolor
if(length(which(iris$Species == "versicolor")) == nrow(iris)){
print("All versicolor")
}else{
print("You have more plants")
}
## [1] "You have more plants"
# Let's redo the queries above using all and any
# We want to know if there is any value of Petal.Length bigger than 6
if(any(iris$Petal.Length > 6)) print("There is")
## [1] "There is"
# We will check now if there are entries of the versicolor family
if(any(iris$Species == "versicolor")) print("Versicolour")
## [1] "Versicolour"
# Now we want to know if all the plants in iris are versicolor
if(all(iris$Species == "versicolor")){
print("All versicolor")
}else{
print("You have more plants")
}
## [1] "You have more plants"
In this tutorial we have learnt how to make our code more simple and readable using the all and any functions