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.

Take your Linux skills to the next level!

How Linux Works

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

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

Become a Bioinformatics Whiz!

Introduction to Bioinformatics Vol. 2

Become a Bioinformatics Whiz! Try Bioinformatics

This is Volume 2 of Bioinformatics Algorithms: An Active Learning Approach. This book presents students with a light-hearted and analogy-filled companion to the author's acclaimed course on Coursera. Each chapter begins with an interesting biological question that further evolves into more and more efficiently solutions of solving it.

$ Check price
49.9949.99Amazon 5 logo(5+ reviews)

More Bioinformatics resources

Ad