Advanced Loops| Dataplexa

Advanced Loops in R

In this lesson, you will go deeper into looping techniques in R.

Advanced loops help you process complex data structures, automate repetitive tasks, and write efficient, readable code for real-world data analysis.


Why Learn Advanced Loops?

Basic loops are useful, but advanced looping concepts allow you to:

  • Work with lists and data frames
  • Apply conditions inside loops
  • Control loop execution flow
  • Improve performance and clarity

Looping Through Lists

Lists are widely used in R to store mixed data types.

Advanced loops allow you to safely iterate through list elements.

items <- list(10, 20, 30, "text", TRUE)

for (item in items) {
  print(item)
}

Using Index-Based Loops

Sometimes you need both the value and its position.

Index-based loops give you full control over iteration.

values <- c(5, 10, 15, 20)

for (i in seq_along(values)) {
  print(paste("Index:", i, "Value:", values[i]))
}

Nested Loops

Nested loops are loops inside other loops.

They are useful when working with multi-dimensional data.

for (i in 1:3) {
  for (j in 1:2) {
    print(paste("Row:", i, "Column:", j))
  }
}

Using break in Loops

The break statement stops a loop immediately.

It is useful when a condition is met early.

for (i in 1:10) {
  if (i == 5) {
    break
  }
  print(i)
}

Using next in Loops

The next statement skips the current iteration.

It allows the loop to continue with the next value.

for (i in 1:6) {
  if (i %% 2 == 0) {
    next
  }
  print(i)
}

Looping Through Data Frames

Data frames are central to data analysis in R.

You can loop through rows or columns depending on your needs.

data <- data.frame(
  name = c("Alex", "Emma", "John"),
  score = c(85, 92, 78)
)

for (i in 1:nrow(data)) {
  print(paste(data$name[i], "scored", data$score[i]))
}

Storing Results Inside Loops

Loops are often used to build new data structures.

Pre-allocating space improves performance.

numbers <- 1:5
squares <- numeric(length(numbers))

for (i in seq_along(numbers)) {
  squares[i] <- numbers[i]^2
}

squares

Common Mistakes in Loops

  • Forgetting to initialize variables
  • Using wrong index ranges
  • Creating infinite loops
  • Not pre-allocating vectors

📝 Practice Exercises


Exercise 1

Write a loop that prints numbers from 1 to 20 but skips multiples of 3.

Exercise 2

Use a nested loop to print a simple multiplication table.

Exercise 3

Loop through a data frame and calculate the average score.

Exercise 4

Store cube values of numbers from 1 to 5 using a loop.


✅ Practice Answers


Answer 1

for (i in 1:20) {
  if (i %% 3 == 0) {
    next
  }
  print(i)
}

Answer 2

for (i in 1:3) {
  for (j in 1:3) {
    print(i * j)
  }
}

Answer 3

total <- 0
for (i in 1:nrow(data)) {
  total <- total + data$score[i]
}
average <- total / nrow(data)
average

Answer 4

nums <- 1:5
cubes <- numeric(length(nums))

for (i in seq_along(nums)) {
  cubes[i] <- nums[i]^3
}

cubes

What’s Next?

In the next lesson, you will learn how to work with Date & Time in R.

Handling time-based data is essential for real-world analytics.