4

Possible Duplicate:
R: generate a repeating sequence based on vector

To create the vector 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 is easy in one line, just type this into the command line and the appropriate output comes out immediately:

c(rep(1:3, 5))

But is there a similarly easy way to produce the vector 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 ?

The pattern of the repetition is different but it's not obvious to me why it's not amenable to a very simple solution. It's possible to do this with a "for" loop without too much difficulty, but can it be all compressed into one "line"?

Community
  • 1
  • 1
  • 1
    Is there a system to name/describe different types of repetition pattern? Unfortunately there were many "R repetitive vector" questions when I searched for duplicates; all I looked at were interested in different patterns. _Which_ pattern was only clear from the examples they used rather than their verbal description, and unfortunately this is a dupe of one that didn't use an obvious example to search by! I'm sure there _must_ be a rich vocabulary to describe the many different kinds of repeat patterns, and it'd be far easier to search by and describe problems with, but where's the dictionary? –  Jul 22 '11 at 17:23
  • "repetitive" is a poor word to search; use "repeat" instead. The first two results of "[r] repeat vector" answer your question... but, again, so does reading the manual. Your question also seems to be guilty of your criticism. – Joshua Ulrich Jul 22 '11 at 18:11
  • Ah, you're right. "Repeat" gives much better search results, thanks. Which is a little weird, as although the pattern is "repetitive" it is _not_ strictly a "repeat pattern" (which is the name used for a structure built out of a single repeating unit) which explains my choice of title (and also why I was reading the wrong help files!). There must be a name for this kind of repetitive pattern, but I don't know it - hence my query above. If I knew what the name was, I'd have searched for it, or failing that, at least given my question a better title! But I hope the example given is clear. –  Jul 22 '11 at 18:51
  • My search suggestion was based solely on my search strategy experience (because people are more likely to use "repeat" when describing and/or answering this question). – Joshua Ulrich Jul 22 '11 at 19:31

1 Answers1

7

You need the each parameter within rep:

> rep(1:5, each = 3)
 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Chase
  • 67,710
  • 18
  • 144
  • 161