๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Sequences

A sequence is a vector whose values follow a steady pattern. R builds sequences with the colon operator and with the seq and rep functions.

Counting up and down

The colon operator counts up from 1 to 5. The second print counts back down from 5 to 1.

print(1:5)
print(5:1)

Stepping with seq

seq starts at 1 and steps by 2. The steps stop at 9.

print(seq(1, 10, by = 2))

A set count of steps

seq spreads five values from 0 to 1. The values land evenly between the two ends.

print(seq(0, 1, length.out = 5))

Repeating a vector

rep makes a longer vector from the pair 1 and 2. The first print repeats the whole pair and the second repeats each value.

print(rep(c(1, 2), times = 2))
print(rep(c(1, 2), each = 2))

Example

evens <- seq(2, 12, by = 2)
print(evens)
print(length(evens))
print(evens[4])

Key points

  • The colon operator counts up by one from the first value to the last.
  • A colon range can also count down by one.
  • seq builds a range with a chosen step size.
  • The by argument of seq sets the size of each step.
  • The length.out argument of seq sets how many values the result holds.
  • rep repeats a vector to make a longer one.
  • The times argument repeats the whole vector as one block.
  • The each argument repeats each value before moving on.

In this example, seq builds the even numbers from 2 to 12. The length call counts six values. Index 4 then picks the fourth value.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does rep(c(1, 2), each = 2) print?