Search⌘ K
AI Features

Solution Review: Relational and Logical Operators

Explore how to apply relational and logical operators in R programming to evaluate conditions and combine tests. Understand different methods to verify if a value falls within a range using boolean logic and operator precedence.

Solution #1: Performing each Test Separately

R
testVariable <- 19
test1 <- testVariable > 4
test2 <- testVariable < 10
result <- test1 && test2
cat(result)

Explanation

Our task was to check whether the testVariable lies between 44 and 1010. For that, we first check whether the number is greater than 44 and store the result in a variable test1. Then we check whether the number is less than 1010 and store the result in variable test2. Later, we take the && of the two variables so that we can check whether both the tests pass or not and print the result.

Solution #2: Using One Boolean Expression

R
testVariable <- 19
cat(testVariable > 4 && testVariable < 10)

Explanation

The above method is simpler. Just use relational and logical operators to make a boolean equation and print the result. R compiler is smart enough to compute the value of testVariable > 4 first then compute the value of testVariable < 10 and later AND their results. This is because the relational operators have higher precedence than logical operators. So, they are executed first and then the logical operators are applied.