Write R code to create a variable score with the value 75. Use an if...else statement to print "Pass" if the score is 50 or higher, and "Fail" otherwise.
Control flow statements allow your code to make decisions based on conditions. The most common control flow statements in R are if
, else
, and switch
.
if
StatementExecutes code only if a condition is TRUE
.
x <- 10
if (x > 5) {
print("x is greater than 5")
}
The if...else
StatementProvides an alternative action if the condition is FALSE
.
x <- 3
if (x > 5) {
print("x is greater than 5")
} else {
print("x is not greater than 5")
}
switch
StatementUseful for selecting one of many options.
day <- "Tuesday"
message <- switch(day,
"Monday" = "Start of the week",
"Tuesday" = "Second day of the week",
"Wednesday" = "Midweek",
"Unknown day"
)
print(message)
Control flow allows you to write more dynamic and flexible R scripts.