Create sequence of repeated values, in sequence?

RRepeatSeqReplicate

R Problem Overview


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!

R Solutions


Solution 1 - R

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)

Solution 2 - R

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

Solution 3 - R

For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.

# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
         x .groups
     <dbl> <fct>  
 1  0.891  1      
 2 -1.13   1      
 3 -0.500  1      
 4 -1.12   1      
 5 -0.0187 1      
 6  0.420  2      
 7 -0.449  2      
 8  0.365  2      
 9  0.526  2      
10  0.466  2      
# … with 17 more rows

There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z") the grouping factor would be c(1,1,2,3,3).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWesley BurrView Question on Stackoverflow
Solution 1 - RDirk EddelbuettelView Answer on Stackoverflow
Solution 2 - RtmfmnkView Answer on Stackoverflow
Solution 3 - RludvigolsenView Answer on Stackoverflow