Practical examples of loops and conditional statements in R

If you work with R for data analysis, sooner or later you’ll need clear, practical examples of loops and conditional statements in R. These control structures are the backbone of automating repetitive tasks, handling messy data, and making your scripts smart enough to react to different situations. Instead of abstract theory, this guide focuses on real examples you can drop straight into your own projects. We’ll walk through examples of loops and conditional statements in R that mirror the way analysts and data scientists actually use the language in 2024 and 2025: cleaning data from APIs, flagging outliers, simulating experiments, and building simple decision logic. Along the way, you’ll see where base R still shines, where the tidyverse and vectorization beat loops, and how to write code that’s readable for your future self and your teammates. Think of this as a hands-on reference you’ll actually keep open while you code.
Written by
Jamie
Published
Updated

Quick, real examples of loops and conditional statements in R

Let’s start directly with concrete code. Below are a few fast examples of loops and conditional statements in R that you’ll recognize from real projects:

## Example 1: Simple for loop with if condition
scores <- c(88, 92, 47, 76, 59)
labels <- character(length(scores))

for (i in seq_along(scores)) {
  if (scores[i] >= 60) {
    labels[i] <- "pass"
  } else {
    labels[i] <- "fail"
  }
}

labels
## Example 2: while loop with conditional stop
balance <- 1000
months  <- 0

while (balance > 0 && months < 24) {
  balance <- balance - 120      # payment
  balance <- balance * 1.01     # interest
  months  <- months + 1
}

balance; months
## Example 3: ifelse for vectorized decisions
temps_f <- c(68, 90, 45, 77)
weather <- ifelse(temps_f >= 80, "hot",
           ifelse(temps_f < 50,  "cold", "mild"))

weather

These are tiny, but they already show how examples of loops and conditional statements in R help you classify values, simulate processes, and encode simple business rules.


Why R users still care about loops in 2024–2025

If you hang around R Twitter or RStudio Community long enough, you’ll hear that you should “avoid for loops” and “vectorize everything.” There’s truth there: vectorized functions and packages like dplyr and data.table are often faster and clearer.

But in modern workflows, the best examples of loops and conditional statements in R usually show up when you:

  • Call APIs or read many files one by one
  • Run simulations or bootstraps
  • Build stepwise algorithms (e.g., gradient descent demos, Markov chains)
  • Implement custom data-cleaning rules that don’t map neatly to one vectorized call

So instead of treating loops as a bad habit, it’s better to learn when to use them and how to keep them clean and readable.


Data-cleaning examples of loops and conditional statements in R

Data cleaning is where many people first need a real example of loops and conditional statements in R. Imagine you’re working with a messy health dataset pulled from a public API. Some values are missing, some are out of range, and you need to flag suspicious rows.

Example: Flagging invalid BMI values with a for loop and if

Suppose you have height and weight in a data frame and want to compute BMI, but also flag obviously wrong entries (like negative height or impossible BMI):

patients <- data.frame(
  id     = 1:6,
  height = c(65, 70, 62, 0, 68, 64),   # inches
  weight = c(150, 180, 120, 140, -5, 200)  # pounds
)

patients$bmi   <- NA_real_
patients$valid <- TRUE

for (i in seq_len(nrow(patients))) {
  h <- patients$height[i]
  w <- patients$weight[i]

  if (h <= 0 || w <= 0) {
    patients$valid[i] <- FALSE
  } else {
    bmi <- (w / (h^2)) * 703  # standard BMI formula in imperial units
    patients$bmi[i] <- bmi

    if (bmi < 10 || bmi > 70) {
      patients$valid[i] <- FALSE
    }
  }
}

patients

This shows how examples of loops and conditional statements in R can encode domain rules: impossible heights, weights, and extreme BMI values get flagged. If you want to cross-check BMI ranges or health guidance, you can compare with resources like the CDC’s BMI information.

Example: Conditional recoding with ifelse instead of a loop

Often you can replace a manual loop with a vectorized conditional, which is usually faster and shorter:

patients\(risk <- ifelse(!patients\)valid, "unknown",
                 ifelse(patients$bmi >= 30, "high",
                 ifelse(patients$bmi >= 25, "medium", "low")))

patients[, c("id", "bmi", "valid", "risk")]

This is still an example of conditional statements in R, just written in a more compact, vectorized style.


File and API automation: examples include loops over resources

A lot of real-world R work in 2024–2025 involves automation: pulling data from multiple sources, reading dozens of CSV files, or hitting an API for every ID in your dataset.

Example: Looping over multiple CSV files with conditional checks

Imagine a folder full of monthly sales files: sales_2024_01.csv, sales_2024_02.csv, and so on. You want to read them all, but skip any file that’s empty or missing required columns.

files <- list.files("data/sales", pattern = "^sales_2024_.*\\.csv$", full.names = TRUE)

all_sales <- data.frame()

for (f in files) {
  dat <- read.csv(f)

#  # Conditional checks on structure
  if (nrow(dat) == 0) {
    message("Skipping empty file: ", f)
    next
  }

  if (!all(c("date", "region", "revenue") %in% names(dat))) {
    warning("File missing columns: ", f)
    next
  }

  all_sales <- rbind(all_sales, dat)
}

nrow(all_sales)

This is a very practical example of loops and conditional statements in R used for data engineering tasks. The next statement lets you skip to the next iteration when a condition fails.

Example: Simple API loop with retry logic

APIs in 2025 still fail randomly. A loop with conditional retry logic is a handy pattern:

library(httr)

ids <- c("A101", "A102", "A103")
results <- list()

for (id in ids) {
  url <- paste0("https://api.example.com/v1/item/", id)

  attempt <- 1
  success <- FALSE

  while (attempt <= 3 && !success) {
    resp <- GET(url)

    if (status_code(resp) == 200) {
      results[[id]] <- content(resp, as = "parsed")
      success <- TRUE
    } else {
      message("Attempt ", attempt, " failed for ", id)
      attempt <- attempt + 1
    }
  }

  if (!success) {
    warning("Failed to fetch id=", id, " after 3 attempts")
  }
}

This nested mix of a for loop and a while loop is one of the best examples of loops and conditional statements in R for real-world resilience: you keep trying until a condition is met or a limit is reached.


Simulation and modeling: classic examples of loops in R

R has a long history in statistics, so many classic examples of loops and conditional statements in R come from simulation and Monte Carlo experiments.

Example: Monte Carlo estimate of a probability

Suppose you want to estimate the probability that a fair die shows six at least once in four rolls. You can simulate this with a loop and a conditional:

set.seed(2025)

trials <- 10000
successes <- 0

for (i in seq_len(trials)) {
  rolls <- sample(1:6, size = 4, replace = TRUE)

  if (any(rolls == 6)) {
    successes <- successes + 1
  }
}

estimate <- successes / trials
estimate

Now you’ve seen another concrete example of loops and conditional statements in R: repeated random experiments plus a conditional counter.

Example: Early stopping in a simulation

Sometimes you don’t know in advance how many iterations you need. You stop when a condition is met.

set.seed(123)

value <- 0
steps <- 0

while (abs(value) < 10 && steps < 10000) {
  value <- value + rnorm(1)
  steps <- steps + 1
}

value; steps

This pattern shows up in optimization, random walks, and Markov chain simulations. The loop runs until either the threshold is reached or a safety cap on iterations is hit.

For deeper statistical background on simulation methods, resources like the NIH’s introductory statistics materials and university lecture notes from sites such as Harvard’s statistics pages are worth bookmarking.


Branching logic: nested conditional statements in R

Sometimes the interesting part isn’t the loop; it’s the branching logic inside. Nested if / else if structures can encode business rules, clinical rules, or decision trees.

Example: Clinical-style risk classification

Say you’re scoring patients into risk buckets based on age and a numeric risk score. This is a simplified example, not a medical guideline; for actual clinical decisions, always consult vetted resources like Mayo Clinic or NIH.

classify_risk <- function(age, score) {
  if (is.na(age) || is.na(score)) {
    return("unknown")
  }

  if (age < 18) {
    return("pediatric")
  } else if (score >= 80) {
    return("very_high")
  } else if (score >= 50) {
    return("high")
  } else if (score >= 20) {
    return("medium")
  } else {
    return("low")
  }
}

ages  <- c(25, 67, 15, 40)
scores <- c(10, 90, 55, NA)

risk_labels <- character(length(ages))

for (i in seq_along(ages)) {
  risk_labels[i] <- classify_risk(ages[i], scores[i])
}

risk_labels

Here, the function itself is just a stack of conditional statements in R. The loop applies it to each row. This kind of pattern is one of the best examples of loops and conditional statements in R for encoding policy or domain logic.


Performance tips: when not to use loops in R

By now you’ve seen a range of examples of loops and conditional statements in R, but there are times when they are not your best move.

In modern R (4.3+), you usually:

  • Prefer vectorized operations (ifelse, logical indexing) for simple elementwise conditions
  • Use apply-family functions (lapply, vapply, purrr::map) for list-like data
  • Reach for dplyr verbs (mutate, case_when, filter) for data frames

Example: Rewriting a loop with vectorized logic

Compare this loop:

x <- -5:5
sign_label <- character(length(x))

for (i in seq_along(x)) {
  if (x[i] < 0) {
    sign_label[i] <- "negative"
  } else if (x[i] > 0) {
    sign_label[i] <- "positive"
  } else {
    sign_label[i] <- "zero"
  }
}

To this vectorized version:

sign_label2 <- ifelse(x < 0, "negative",
               ifelse(x > 0, "positive", "zero"))

Both are valid examples of conditional statements in R. The second one is shorter and usually faster. In data frame workflows, you might instead write:

library(dplyr)

df <- data.frame(x = -5:5)

df <- df %>%
  mutate(sign_label = case_when(
    x < 0  ~ "negative",
    x > 0  ~ "positive",
    TRUE   ~ "zero"
  ))

The idea in 2024–2025 is not to avoid loops dogmatically, but to recognize patterns where other tools do a better job.


Error handling: examples include tryCatch with conditionals

In production scripts, you want to catch and handle errors instead of crashing. That’s where error-aware examples of loops and conditional statements in R come in.

Example: Loop over files with tryCatch and conditional logging

files <- c("good.csv", "missing.csv", "corrupt.csv")
results <- list()

for (f in files) {
  dat <- tryCatch(
    read.csv(f),
    error = function(e) {
      message("Error reading ", f, ": ", e$message)
      NULL
    }
  )

  if (!is.null(dat)) {
    results[[f]] <- dat
  }
}

The conditional if (!is.null(dat)) ensures that only successfully read files are stored. This pattern is common in ETL pipelines and scheduled jobs.


FAQ: common questions about examples of loops and conditionals in R

What are some simple examples of loops and conditional statements in R for beginners?

Two of the simplest patterns are:

## Counting with a for loop
for (i in 1:5) {
  print(i)
}

## Basic if / else
x <- 10
if (x > 0) {
  message("Positive")
} else {
  message("Zero or negative")
}

These tiny snippets are the building blocks for the more advanced examples you’ve seen above.

Is there a real-world example of loops and conditional statements in R for data science?

Yes. A very common one is looping over model hyperparameters and tracking the best result:

library(stats)

best_rmse <- Inf
best_lambda <- NA

for (lambda in c(0.01, 0.1, 1, 10)) {
  fit <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width,
            data = iris)

#  # pretend we regularize using lambda and compute RMSE
  rmse <- sqrt(mean(residuals(fit)^2)) + lambda * 0.001

  if (rmse < best_rmse) {
    best_rmse <- rmse
    best_lambda <- lambda
  }
}

best_lambda; best_rmse

Here the loop explores options, and the conditional keeps track of the current best model.

Are loops always slower than vectorized code in R?

No. R’s loops have improved a lot over the years, and for moderate data sizes they’re often fast enough. Vectorized code is still typically faster and cleaner, but in many scripts the real bottleneck is I/O (reading files, hitting APIs), not the loop itself. Use simple benchmarks (system.time, bench package) if performance truly matters.

How can I learn more about writing reliable R code with control flow?

Official R documentation on control structures (?Control) is a good starting point. Many university R courses host their lecture notes online; searching for “R control structures course notes” often leads to high-quality material from .edu domains. For statistical and methodological context, resources from organizations like the National Institutes of Health and Harvard’s statistics department are helpful complements.


You’ve now seen a wide range of practical examples of loops and conditional statements in R: data cleaning, file processing, API calls, simulations, risk scoring, and error handling. The pattern is always the same: use loops when you need step-by-step control, use conditional statements to make decisions, and don’t hesitate to switch to vectorized or tidyverse tools when they express your intent more clearly.

Explore More R Code Snippets

Discover more examples and insights in this category.

View All R Code Snippets