Reputation: 1848
I want to make such a loop using R.
for i=1 output will be
1
2
3
for i=2 output will be
2
3
1
for i=3 output will be
3
1
2
Namely the outputs are successive integers. It is just when the integer reaches 4 it returns 1 and goes on. I guess I must use modular operations, how can I do that?
Upvotes: 0
Views: 47
Reputation: 12559
This is my solution:
f <- function(i) { x <- i:(i+2) %% 3; x[x==0] <- 3; x }
for (i in 1:5) print(f(i))
Here is a second solution:
r <- matrix(c(3,1,2, 1,2,3, 2,3,1),3)
for (i in 1:5) print(r[i %% 3 + 1,])
Upvotes: 2
Reputation: 206243
If you have
a <- 1:3
for a value if i
, you get the the sequence with
f <- function(i) (a+i+1) %% length(a) +1
f(1)
# [1] 1 2 3
f(2)
# [1] 2 3 1
f(3)
# [1] 3 1 2
f(4)
# [1] 1 2 3
Note that it starts over again at 4
Upvotes: 3