Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R sequence automation

Tags:

r

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?

like image 270
user2007598 Avatar asked Feb 23 '26 05:02

user2007598


1 Answers

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
like image 96
josliber Avatar answered Feb 25 '26 18:02

josliber