0 votes
1 view
in R Programming by (5.3k points)

This is a very basic question, but it's annoying me, so I'm asking.

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 that will do it, but this also seems clumsy -- there should be an intrinsic way to do this!

1 Answer

0 votes
by (25.3k points)

To create a sequence of repeated values in R, you can use the each argument in the rep function to specify the number of iterations of the value.

In your case:

rep(1:8, each=20)

  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3

 [49] 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5

 [97] 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8

[145] 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...