R for Spatial Statistics

 

Boolean Values, Comparisons, and "If" Statements

Logical (Boolean) Values

Boolean values in R can be TRUE or FALSE. Booleans are typically used as the result of a comparison. The code below will set the variable "Temp" equal to "TRUE" if x is greater than 13 and "FALSE" otherwise.

Temp = x > 13

Comparisons

Below is a table of the comparisons that are available in R.

Operator Description
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equals to
!= Not equals to

 

Boolean Operators

Multiple boolean values, or the results from comparisons can be combined using the following boolean operators.

Operator Name Description
& AND TRUE if both values are TRUE, FALSE otherwise
| (pipe or vertical bar) OR TRUE if either values are TRUE, FALSE otherwise
! NOT TRUE becomes FALSE, FALSE becomes TRUE

 

"if" Statements

If statements use boolean values and/or comparison operators to select whether a particular set of code should be executed or not. Try the following code and then change the value of x.

x=10
if (x<12) print("X is less than 12")

When you want to selectivity execute multiple lines of code, use braces to group the code together as shown below.

if (x<12)
{
    print("X is less than 12")
}
else
{
    print("X is greater than or equal to 12")
}