R Tutorial menu

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

r
marks <- 64

if (marks >= 80) {
  print("Grade A")
} else if (marks >= 60) {
  print("Grade B")
} else {
  print("Try again")
}
Output
[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

r
marks <- c(85, 45, 70)
ifelse(marks >= 50, "Pass", "Fail")
Output
[1] "Pass" "Fail" "Pass"

For Loops

A for loop runs once for each item of a vector:

Example

r
for (city in c("Karachi", "Lahore", "Peshawar")) {
  cat("Delivery available in", city, "\n")
}

total <- 0
for (i in 1:5) {
  total <- total + i
}
total
Output
Delivery 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

r
savings <- 1000
months <- 0
while (savings < 5000) {
  savings <- savings + 1500
  months <- months + 1
}
cat("Months needed:", months, "\n")
Output
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

KeywordWhat it does
breakStops the loop completely
nextSkips the rest of this round and goes to the next item

Example

r
for (n in 1:10) {
  if (n %% 2 == 0) next   # skip even numbers
  if (n > 7) break        # stop after 7
  cat(n, "")
}
Output
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

r
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))
Output
[1] 1180
[1] 1050
[1]  295  590 1416

The Parts of a Function

PartIn the example
Nameadd_gst
Argumentsprice and rate
Default valuerate = 0.18, used when you do not give a rate
BodyThe code inside { }
Return valuereturn(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

r
square <- function(x) x^2
square(9)
Output
[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

r
grade <- function(m) {
  if (m >= 80) "A" else if (m >= 60) "B" else "C"
}
sapply(c(85, 72, 40), grade)
Output
[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

r
result <- tryCatch(
  log(-1),
  warning = function(w) "Cannot take the log of a negative number"
)
result
Output
[1] "Cannot take the log of a negative number"

Exercise

Exercise

What does a function in R return if there is no return() call?

Learn R with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp