Title here
Summary here
Our first example demonstrates the use of if/else statements in R. Here’s the full source code:
# Here's a basic example.
if (7 %% 2 == 0) {
print("7 is even")
} else {
print("7 is odd")
}
# You can have an if statement without an else.
if (8 %% 4 == 0) {
print("8 is divisible by 4")
}
# Logical operators like && and || are often useful in conditions.
if (8 %% 2 == 0 || 7 %% 2 == 0) {
print("either 8 or 7 are even")
}
# In R, we can use ifelse() for simple conditional statements.
num <- 9
result <- ifelse(num < 0, paste(num, "is negative"),
ifelse(num < 10, paste(num, "has 1 digit"),
paste(num, "has multiple digits")))
print(result)
To run the program, save the code in a file (e.g., if_else.R
) and use the Rscript
command:
$ Rscript if_else.R
[1] "7 is odd"
[1] "8 is divisible by 4"
[1] "either 8 or 7 are even"
[1] "9 has 1 digit"
Note that in R:
%%
for the modulo operation.print()
function is used instead of fmt.Println()
.ifelse()
function, which is similar to the ternary operator in other languages. It can be nested for multiple conditions.{}
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.