R If Else, Loops and Functions
Decisions, loops and functions let your R code choose what to do, repeat work and reuse steps.
If, Else If and Else
The condition goes in round brackets, and the code to run goes in curly braces:
Example
marks <- 64
if (marks >= 80) {
print("Grade A")
} else if (marks >= 60) {
print("Grade B")
} else {
print("Try again")
}[1] "Grade B"
R checks each condition from top to bottom and runs only the first block that is TRUE.
Keep else on the same line as the closing brace }. If else starts a new line at the top level, R thinks the if has already ended and gives an error.
If for a Whole Vector
if checks only one value. For a whole vector, use ifelse():
Example
marks <- c(85, 45, 70)
ifelse(marks >= 50, "Pass", "Fail")[1] "Pass" "Fail" "Pass"
For Loops
A for loop runs once for each item of a vector:
Example
for (city in c("Karachi", "Lahore", "Peshawar")) {
cat("Delivery available in", city, "\n")
}
total <- 0
for (i in 1:5) {
total <- total + i
}
totalDelivery available in Karachi Delivery available in Lahore Delivery available in Peshawar [1] 15
While Loops
A while loop repeats as long as its condition is TRUE. Ayesha has Rs 1,000 and saves Rs 1,500 each month. How many months until she has at least Rs 5,000?
Example
savings <- 1000
months <- 0
while (savings < 5000) {
savings <- savings + 1500
months <- months + 1
}
cat("Months needed:", months, "\n")Months needed: 3
Make sure something inside the loop changes the condition, or the loop will never end. Press Esc in RStudio to stop a stuck loop.
Break and Next
| Keyword | What it does |
|---|---|
break | Stops the loop completely |
next | Skips the rest of this round and goes to the next item |
Example
for (n in 1:10) {
if (n %% 2 == 0) next # skip even numbers
if (n > 7) break # stop after 7
cat(n, "")
}1 3 5 7
In R you often do not need a loop at all. sum(1:5) gives the same answer as the for loop above. Vector operations are shorter and much faster, so try them first.
Writing Your Own Functions
Create a function with the word function, and store it in a variable like any other value:
Example
add_gst <- function(price, rate = 0.18) {
total <- price + price * rate
return(round(total))
}
add_gst(1000)
add_gst(1000, rate = 0.05)
add_gst(c(250, 500, 1200))[1] 1180 [1] 1050 [1] 295 590 1416
The Parts of a Function
| Part | In the example |
|---|---|
| Name | add_gst |
| Arguments | price and rate |
| Default value | rate = 0.18, used when you do not give a rate |
| Body | The code inside { } |
| Return value | return(round(total)) |
If you leave out return(), R returns the value of the last line of the body. Many R programmers write short functions this way:
Example
square <- function(x) x^2
square(9)[1] 81
Because the function uses vector maths, it works on a single price or on a whole vector of prices.
Applying a Function to Every Item
sapply() runs a function on each item of a vector and collects the results:
Example
grade <- function(m) {
if (m >= 80) "A" else if (m >= 60) "B" else "C"
}
sapply(c(85, 72, 40), grade)[1] "A" "B" "C"
Related functions are lapply() (always returns a list) and apply() (works on the rows or columns of a matrix).
Handling Errors
tryCatch() lets your code continue when something goes wrong:
Example
result <- tryCatch(
log(-1),
warning = function(w) "Cannot take the log of a negative number"
)
result[1] "Cannot take the log of a negative number"
Exercise
Exercise
What does a function in R return if there is no return() call?
