I want to generate a new vector by repeating the elements of a vector. What R function should I use?

E.g.

a= [1,2,3]

to

a=[1,1,2,2,3,3]

E.g.

a= [1,2,3]

to

a=[1,1,2,2,3,3]

+1 vote

Best answer

You can use **rep()** function to repeat elements of a vector or the whole vector itself.

E.g.

To repeat each element the same number of times, you can use the argument **"each**" as follows:

> a <- c(1,2,3)

> b <- rep(a, each=3)

> b

[1] 1 1 1 2 2 2 3 3 3

To repeat each elements a different number of times, you can use the argument "**times**" as follows:

> d <- rep(a, times=c(3,4,5))

> d

[1] 1 1 1 2 2 2 2 3 3 3 3 3

To repeat the whole vector, you can use the argument "**times**" as follows:

> c <- rep(a, times=3)

> c

[1] 1 2 3 1 2 3 1 2 3