0Pricing
R Academy · Lesson

The Colon Operator for Integer Ranges

Use the colon operator to create integer sequences quickly.

The Colon Operator

The : operator generates an integer sequence from a start value to an end value, incrementing by 1 (or -1 for descending). It is the fastest and most concise way to create a range in R.

# Basic integer range
ones_to_ten <- 1:10
cat('1 to 10:', ones_to_ten, '
')

# Descending range
ten_to_one <- 10:1
cat('10 to 1:', ten_to_one, '
')

Using : in for Loops

The colon operator is most commonly used in for loop counters. It creates the sequence inline without needing a separate variable, keeping your code concise.

# Classic for loop with colon range
total <- 0
for (i in 1:5) {
  total <- total + i
  cat('i =', i, ', running total =', total, '
')
}
cat('Sum of 1 to 5:', total, '
')

All lessons in this course

  1. The Colon Operator for Integer Ranges
  2. seq() for Custom Sequences
  3. rep() for Repeating Values
  4. Named Vectors and Named Sequences
← Back to R Academy