How to Successfully Follow Naming Conventions in R
How to Configure R
How to Fix Data Reading Errors in R

How to Repeat Vectors in R

In R, you can combine a vector with itself if you want to repeat it, but if you want to repeat the values in a vector many times, using the c() function becomes a bit impractical. R makes life easier by offering you a function for repeating a vector: rep().

You can use the rep() function in several ways. If you want to repeat the complete vector, for example, you specify the argument times. To repeat the vector c(0, 0, 7) three times, use this code:

> rep(c(0, 0, 7), times = 3)
[1] 0 0 7 0 0 7 0 0 7

You also can repeat every value by specifying the argument each, like this:

> rep(c(2, 4, 2), each = 3)
[1] 2 2 2 4 4 4 2 2 2

R has a little trick up its sleeve. You can tell R for each value how often it has to be repeated. To take advantage of that magic, tell R how often to repeat each value in a vector by using the times argument:

> rep(c(0, 7), times = c(4,2))
[1] 0 0 0 0 7 7

And you can, like in seq, use the argument length.out to tell R how long you want it to be. R will repeat the vector until it reaches that length, even if the last repetition is incomplete, like so:

> rep(1:3,length.out=7)
[1] 1 2 3 1 2 3 1
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Create and Assign Named Vectors in R
How to Dispatch to a Method in R
How to Add Color and a Key to Lattice Charts in R
How to Present Dates in Different Formats in R
How to Make a Minimal Reproducible Example to Get Help with R