+2 votes
in Programming Languages by (40.5k points)
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]

1 Answer

+1 vote
by (349k points)
selected by
 
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

Related questions

+4 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer

...