Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create sequence of repeated values, in sequence?

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?

  • I tried nesting seq() and rep() but that didn't quite do what I wanted.
  • I can obviously write a for-loop to do this, but there should be an intrinsic way to do this!
like image 483
Wesley Burr Avatar asked Jun 21 '11 21:06

Wesley Burr


People also ask

Can a sequence have repeated values?

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.

How do I create a sequence of numbers in R?

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).

How do you make a repeated number a vector in R?

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.

How do you repeat a number multiple times in R?

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.


2 Answers

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) 
like image 192
Dirk Eddelbuettel Avatar answered Sep 18 '22 06:09

Dirk Eddelbuettel


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 
like image 44
tmfmnk Avatar answered Sep 18 '22 06:09

tmfmnk