Programming

Loops, Conditionals, Functions, and Beyond

Author

Raju Rimal

Published

June 11, 2026

Now that you’ve installed R and are familiar with its basic interface, it’s time to dive deeper into the core programming constructs that make R a powerful tool. This guide introduces conditionals, loops, functions, and other foundational concepts that will help you write efficient and reusable code. Mastering these basics will set the stage for more advanced topics like data manipulation and analysis.


1. Conditionals: Making Decisions in R

Conditionals are essential for decision-making in code. They allow you to execute different actions based on certain conditions.

The if Statement

The if statement checks a condition and executes the code inside its block if the condition is TRUE.

x <- 10

if (x > 5) {
  print("x is greater than 5")
}
[1] "x is greater than 5"

The if...else Statement

Use else to provide an alternative block of code when the condition is FALSE.

x <- 3

if (x > 5) {
  print("x is greater than 5")
} else {
  print("x is not greater than 5")
}
[1] "x is not greater than 5"

ifelse for Vectorized Operations

The ifelse function applies a condition to every element of a vector.

numbers <- c(2, 5, 8)
result <- ifelse(numbers > 5, "High", "Low")
print(result)
[1] "Low"  "Low"  "High"

Nested Conditionals

Combine multiple conditions with if, else if, and else.

x <- -1

if (x > 0) {
  print("Positive")
} else if (x == 0) {
  print("Zero")
} else {
  print("Negative")
}
[1] "Negative"

2. Loops: Repeating Tasks

Loops let you repeat a block of code multiple times, making them invaluable for automation.

The for Loop

Iterates over a sequence of numbers, vectors, or lists.

for (i in 1:5) {
  print(paste("Iteration:", i))
}
[1] "Iteration: 1"
[1] "Iteration: 2"
[1] "Iteration: 3"
[1] "Iteration: 4"
[1] "Iteration: 5"

The while Loop

Executes as long as a condition is TRUE.

x <- 1

while (x <= 5) {
  print(x)
  x <- x + 1
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

The repeat Loop

Repeats indefinitely until a break statement is encountered.

x <- 1

repeat {
  print(x)
  x <- x + 1
  if (x > 5) break
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

Looping Over Vectors and Lists

Use loops to iterate through more complex objects:

fruits <- c("Apple", "Banana", "Cherry")

for (fruit in fruits) {
  print(fruit)
}
[1] "Apple"
[1] "Banana"
[1] "Cherry"

3. Functions: Writing Reusable Code

Functions allow you to encapsulate code logic, making it reusable and modular.

Defining a Function

Use the function keyword to define your own functions.

add_numbers <- function(a, b) {
  return(a + b)
}

result <- add_numbers(3, 7)
print(result)
[1] 10

Default Arguments

You can set default values for function arguments.

greet <- function(name = "Guest") {
  return(paste("Hello,", name))
}

print(greet())
[1] "Hello, Guest"
print(greet("Alice"))
[1] "Hello, Alice"

Returning Multiple Values

Return a list to output multiple values from a function.

calculate <- function(a, b) {
  sum <- a + b
  product <- a * b
  return(list(sum = sum, product = product))
}

result <- calculate(3, 5)
print(result$sum)
[1] 8
print(result$product)
[1] 15

4. Other Essential Concepts

Vectors and Vectorized Operations

Vectors are a fundamental data structure in R. R’s operations are vectorized, meaning you can perform operations on entire vectors at once.

numbers <- c(1, 2, 3, 4)

# Element-wise addition
result <- numbers + 2
print(result)
[1] 3 4 5 6

The apply Family of Functions

Instead of using loops, R provides the apply, lapply, sapply, and other functions for applying operations to data structures.

Using apply on Matrices:

matrix <- matrix(1:9, nrow = 3)

# Sum of each row
row_sums <- apply(matrix, 1, sum)
print(row_sums)
[1] 12 15 18

Using lapply on Lists:

numbers <- list(a = 1:3, b = 4:6)

# Calculate the sum of each element in the list
sums <- lapply(numbers, sum)
print(sums)
$a
[1] 6

$b
[1] 15

5. Working with Data Structures

Data Frames

A data frame is like a table where each column can have different types.

data <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(25, 30, 35),
  Score = c(90, 85, 88)
)

print(data)
     Name Age Score
1   Alice  25    90
2     Bob  30    85
3 Charlie  35    88

Subsetting Data

Extract rows, columns, or specific values.

# Select a column
print(data$Age)
[1] 25 30 35
# Select specific rows and columns
print(data[1:2, c("Name", "Score")])
   Name Score
1 Alice    90
2   Bob    85

Lists

Lists can hold different types of data.

list_data <- list(
  Name = "Alice",
  Age = 25,
  Scores = c(90, 85, 88)
)

print(list_data$Scores)
[1] 90 85 88

6. Error Handling

R provides tools for handling errors gracefully.

Using tryCatch

safe_divide <- function(a, b) {
  tryCatch({
    result <- a / b
    return(result)
  }, warning = function(w) {
    print("Warning occurred")
  }, error = function(e) {
    print("Error occurred")
  })
}

safe_divide(10, 0)
[1] Inf

7. Best Practices for Writing R Code

  1. Comment Your Code: Add meaningful comments for clarity.
  2. Use Meaningful Variable Names: Avoid ambiguous names like x or y.
  3. Indentation and Formatting: Make your code readable.
  4. Test Your Functions: Validate them with different inputs.
  5. Avoid Unnecessary Loops: Use vectorized operations and apply functions whenever possible.

Next Steps

Once you are comfortable with these programming concepts, you’re ready to explore more advanced topics like:

  • Data manipulation with dplyr
  • Visualization with ggplot2
  • Statistical modeling and machine learning

These foundations will make it easier to understand and implement sophisticated analysis techniques.


Conclusion

R’s programming fundamentals, like conditionals, loops, and functions, form the building blocks of your data journey. By mastering these concepts, you’ll be well-prepared to handle more complex data tasks with confidence.