Rep function in R

When I execute:

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 output length) 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 strange. I think both of these commands should perform the same function. Can anybody help?

Thanks!

+6
source share
2 answers

From ?rep

'length.out can be specified instead of "times", in which case x is repeated as many times as necessary to create the vector this length. If both are given, 'length.out takes precedence and' is ignored.

+14
source

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

-1
source

Source: https://habr.com/ru/post/922396/


All Articles