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.

Become a Bioinformatics Whiz!

Bioinformatics Data Skills

Become a Bioinformatics Whiz! Try Bioinformatics

Learn the best practices used by academic and industry professionals. Bioinformatics Data Skills give a great overview to the Linux Command Line, Github, and other essential tools used in the trade. This book bridges the gap between knowing a few programming languages and being able to utilize the tools to analyze large amounts of biological data.

$ Check price
49.9949.99Amazon 4.5 logo(7+ reviews)

More Bioinformatics resources

Take your Linux skills to the next level!

Linux for Beginners

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

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(101+ reviews)

More Linux & UNIX resources

Ad