rep function in R
Asked Answered
P

2

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!

Pice answered 8/8, 2012 at 18:10 Comment(1)
have you read the help page ?repDioscuri
D
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.

Dioscuri answered 8/8, 2012 at 18:15 Comment(3)
But look at the each argument to see if that gives the output that you want.Cauvery
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!Pice
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!)Outflow
C
-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).

Cosh answered 9/5, 2014 at 2:13 Comment(2)
technically correct, but ugh! much better practice to use named arguments rather than placeholders (,,)Asseverate
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.Leigh

© 2022 - 2024 — McMap. All rights reserved.