Here we show how to use the rep() function for replication and the seq() function for sequence generation in R.

1 Using rep() for Replication

To replicate a vector or a factor in R, we can use the rep() function from the "base" package.

Using the "vec" vector below.

vec = c(1, 2, 3)

To replicate it two times:

rep(vec, times = 2)
[1] 1 2 3 1 2 3
# Similarly, we do not need to name the "times" argument:
rep(vec, 2)
[1] 1 2 3 1 2 3

To replicate each element two times:

rep(vec, each = 2)
[1] 1 1 2 2 3 3

To replicate the vector until we have 8 elements:

rep(vec, length = 8)
[1] 1 2 3 1 2 3 1 2

To replicate each element two times and the resulting vector two times:

rep(vec, each = 2, times = 2)
 [1] 1 1 2 2 3 3 1 1 2 2 3 3

To replicate each element two times until we have 8 elements:

rep(vec, each = 2, length = 8)
[1] 1 1 2 2 3 3 1 1

2 Using seq() for Sequence Generation

To generate a sequence in R, we can use the seq() function from the "base" package.

For a sequence from 1 to 5:

seq(from = 1, to = 5)
[1] 1 2 3 4 5
# Similarly, we can do any of these:
seq(1, 5)
seq(1:5)
seq(5)
1:5
[1] 1 2 3 4 5

We can set the difference or gap between each element with the "by" argument:

# By 0.5
seq(1, 5, by = 0.5)
[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
# Similarly, we can do this:
seq(1, 5, 0.5)
[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
# By 1.5
seq(1, 5, by = 1.5)
[1] 1.0 2.5 4.0

We can set the number of elements in the sequence to 9:

seq(1, 5, length.out = 9)
[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

We can set the number of elements in the sequence to the length of another vector:

# With a vector of length = 3
vec = c("A", "B", "C")
seq(1, 5, along.with = vec)
[1] 1 3 5

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes