Our first example demonstrates the use of if/else statements in R. Here’s the full source code:
To run the program, save the code in a file (e.g., if_else.R) and use the Rscript command:
Note that in R:
We use %% for the modulo operation.
The print() function is used instead of fmt.Println().
R doesn’t have a direct equivalent to Go’s ability to declare and initialize a variable in the if statement. Instead, we declare the variable before the if statement.
R provides the ifelse() function, which is similar to the ternary operator in other languages. It can be nested for multiple conditions.
In R, you don’t need parentheses around conditions, but they are often used for clarity. Curly braces {} are required for multi-line blocks.
R also provides the switch() function for more complex conditional execution, which we’ll explore in the next example.