rep function in R

r rep
Vinayak Agarwal picture Vinayak Agarwal · Aug 8, 2012 · Viewed 32.3k times · Source

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!

Answer

GSee picture GSee · Aug 8, 2012

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.