I need a sequence of repeated numbers, i.e. 1 1 ... 1 2 2 ... 2 3 3 ... 3 etc.
The way I implemented this was:
nyear <- 20 names <- c(rep(1,nyear),rep(2,nyear),rep(3,nyear),rep(4,nyear), rep(5,nyear),rep(6,nyear),rep(7,nyear),rep(8,nyear))
which works, but is clumsy, and obviously doesn't scale well.
How do I repeat the N integers M times each in sequence?
seq()
and rep()
but that didn't quite do what I wanted.To repeat a sequence of numbers in R you can use the rep() function. For example, if you type rep(1:5, times=5) you will get a vector with the sequence 1 to 5 repeated 5 times.
The simplest way to create a sequence of numbers in R is by using the : operator. Type 1:20 to see how it works. That gave us every integer between (and including) 1 and 20 (an integer is a positive or negative counting number, including 0).
There are two methods to create a vector with repeated values in R but both of them have different approaches, first one is by repeating each element of the vector and the second repeats the elements by a specified number of times. Both of these methods use rep function to create the vectors.
In R, the easiest way to repeat rows is with the REP() function. This function selects one or more observations from a data frame and creates one or more copies of them. Alternatively, you can use the SLICE() function from the dplyr package to repeat rows.
You missed the each=
argument to rep()
:
R> n <- 3 R> rep(1:5, each=n) [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 R>
so your example can be done with a simple
R> rep(1:8, each=20)
Another base R
option could be gl()
:
gl(5, 3)
Where the output is a factor:
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 Levels: 1 2 3 4 5
If integers are needed, you can convert it:
as.numeric(gl(5, 3)) [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With