HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RVariablesData TypesOperatorsCharacters (character)VectorsConditions (if / else)Loops (for / while)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables & Types
🔢 Numbers & Math
✍️ Character
📚 Vector
🔀 Condition & Loop
if / elseforwhile
🧩 Function
R›REFERENCE›Condition & Loop
🔀

Condition & Loop

if/else, for, and while.

CommandDescription
if / elseBranching based on conditions.
forRanges and vector iteration.
whileRepeats as long as the condition is true.

if / else

Try it yourself →

Branching based on conditions.

Syntax

if (condition) { ... } else { ... }

Description

The condition is written in parentheses; if true, the first block executes. else must be on the SAME line as the closing }.

Example

age <- 20
if (age >= 18) {
  cat("Adult\n", sep="")
} else {
  cat("Child\n", sep="")
}

Expected output

Adult

When to use?

Decision making, input control.

Common mistakes

  • ⚠️ Putting else on a new line causes an error; use } else { on the same line.

for

Try it yourself →

Ranges and vector iteration.

Syntax

for (i in 1:n) { ... }   //   for (x in v) { ... }

Description

The range 1:5 includes 5 as well. for-in iterates through the elements of a vector in order.

Example

for (i in 1:3) {
  cat(i, "\n", sep="")
}

Expected output

1
2
3

When to use?

Repetitive tasks (though vectorization is generally preferred in R).

while

Try it yourself →

Repeats as long as the condition is true.

Syntax

while (condition) { ... }

Description

while is used when the number of iterations is not known in advance. R doesn't have i++; you write i <- i + 1.

Example

n <- 0
while (n < 3) {
  cat(n, "\n", sep="")
  n <- n + 1
}

Expected output

0
1
2

When to use?

Conditional repetition.

Common mistakes

  • ⚠️ Forgetting to increment (n <- n + 1) creates an infinite loop.
HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code