02. Sequences and Repetitions in R seq(), rep()

To avoid repetitiveness and tediously filling the elements of a vector, we may use the seq() and rep() functions.

Sequences

We can create a vector with a known pattern or sequence with either the seq() command or : notation.

1) : (colon) notation

The : is used to indicate a sequence of integer values.

> x <- c(1:9)
> x
[1] 1 2 3 4 5 6 7 8 9

2) seq() function

To get more specific, we can use the seq() function.

> x <- seq(from=15, to=45, by=3)
> x
[1] 15 18 21 24 27 30 33 36 39 42 45

Notice how the values from and to are inclusive.

We can also use length parameter instead, which will equally split our sequence.

> x <- seq(from=1.1, to=3, length=20)
[1] 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0 2.1
[12] 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 3.0
# Every tenth number up to 100
> 1:10*10
[1] 10 20 30 40 50 60 70 80 90 100

Remember that you can open the manual page for any function by typing ?seq

Indexing with Sequences

Indexing can be performed not just to return one value, but multiple. We can do this using the seq() function above.

> x <-seq(1:20)
# Pull out just the first five elements
> x[1:5]
[1] 1 2 3 4 5
# Pull out every third element
> x[seq(1,20,3)]
[1] 1 4 7 10 13 16 19

Repetitions

R also allows you to easily create vectors containing repetitions with the rep() function.

> x <- rep(c("hello there"), 4)
> x
[1] "hello there" "hello there" "hello there"
[4] "hello there"

The first parameter is the constant to be repeated, while the second parameter is the number of times.

Learn to be a Pythonista!

Python Playground

Learn to be a Pythonista! Try Python

Python Playground is a collection of fun programming projects that will inspire you to new heights. You'll manipulate images, build simulations, and interact with hardware using Arduino & Raspberry Pi. With each project, you'll get familiarized with leveraging external libraries for specialized tasks, breaking problems into smaller, solvable pieces, and translating algorithms into code.

$ Check price
29.9529.95Amazon 4 logo(14+ reviews)

More Python resources

Take your Linux skills to the next level!

The Linux Command Line

Take your Linux skills to the next level! Try Linux & UNIX

The Linux Command Line takes you from your very first terminal keystrokes to writing full programs in Bash, the most popular Linux shell. Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with regular expressions, and more.

$ Check price
39.9539.95Amazon 4.5 logo(274+ reviews)

More Linux & UNIX resources

Ad