6

When I perform:

rep(1:4, rep(4,4))

I get

1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 

which is expected. But then when I try to fix the length to 16(which is the length of the output) as follows:

rep(1:4, rep(4,4), length.out = 16)

I get

1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4

which is weird. I think both of these commands should perform the same function. Can someone please help?

Thanks!

Vinayak Agarwal
  • 1,350
  • 3
  • 15
  • 28

2 Answers2

14

From ?rep

‘length.out’ may be given in place of ‘times’, in which case ‘x’ is repeated as many times as is necessary to create a vector of this length. If both are given, ‘length.out’ takes priority and ‘times’ is ignored.

GSee
  • 48,880
  • 13
  • 125
  • 145
  • But look at the `each` argument to see if that gives the output that you want. – Greg Snow Aug 08 '12 at 21:40
  • Thanks GSee. I did not read the whole help documentation. However,what was troubling me was that if I specify **rep(1:4, each = 4, length = 20)**, then I get **1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 1 1 1 1** but I guess it turns out that if **each=4** is replaced with **rep(4,4)**, then the print method is different, even though both each and rep() should fulfill the same purpose here. Thanks! – Vinayak Agarwal Aug 08 '12 at 23:29
  • 1
    You need to read `?rep` thoroughly. What do you mean by the `print` method? `rep(1:4, each = rep(4,4), length = 20)` gives you a warning which is self explanatory (especially if you read the help!) – mnel Aug 09 '12 at 04:37
-2

rep(1:4,,rep(4,4),length.out=16) will give the result you are looking for. A simpler way to write this is rep(1:4,,16,4).

cf-
  • 8,598
  • 9
  • 36
  • 58
minhaj
  • 1
  • 1
  • 6
    technically correct, but ugh! much better practice to use named arguments rather than placeholders (`,,`) – Ben Bolker May 09 '14 at 02:16
  • 1
    I'm not sure this is even *technically* correct. It works on the R instance on the computer I'm typing this on (a couple years old: 2.15), but I get a warning message that suggests that it's only by accident ("Warning: first element used of 'each' argument"). Also, the order of parameters beyond the first two isn't documented at all, so I don't think there's any guarantee it won't break in a future revision. – zwol May 09 '14 at 02:40