c(2:5,
1:1,
3:5,
1:2,
4:5,
1:3,
5:5,
1:4)
> 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4.
As one can see there is a pattern here. Starting at n=5 n-3:n, counting down and then followed by 1:n-4 and so on. My question is there any way to automate this using seq() and rep() in R?
I guess you could view this as a loop of some variable d from 3 to 0 where for each value d you add the following two vectors:
(n-d):n
1:(n-d-1)
Armed with this analysis, we can pretty easily perform this as a one-liner:
n <- 5
as.vector(sapply(3:0, function(d) c((n-d):n, 1:(n-d-1))))
# [1] 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4
Another way that would be a bit more efficient but in my opinion less understandable could use outer and modulo:
as.vector(outer(0:(n-1), 3:0, function(x, y) (x-y-1) %% n + 1))
# [1] 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With