Julia equivalent to R's rep(..., length.out)

Copy-pasting a slack discussion for people who might need this:

Can we add a length_out feature to the repeat function?
In R, I can do rep(1:3, length.out = 4), which gives 1 2 3 1 . It would be cool if repeat can do that.

Answer given by Alex Arslan:
You can do something like

using Base.Iterators
collect(take(flatten((repeated(1:3))), 4))

You can drop the flatten if you use cycle instead of repeated:

collect(Iterators.take(Iterators.cycle(1:3), 4))

How would this work for multiple dimensions?

almost sure that cyclying behaviour is 1D only. All higher D get mapped to 1D and then cycled.

I would do it this way:

a = repeat(1:3,2)[1:4]
1 Like

I disagree. I think that R’s “let’s try to recycle elements until needed” approach is a misfeature.

The solutions in this topic work fine when needed, but actually it is a very rare use case, and can hide length mismatch bugs (like pretty much all of R’s “recycling” semantics).