Running the snippet D=1;for (j in 1:5){D=(D-1)%%4;print(D)}
I get the expected outcome:
[1] 0
[1] 3
[1] 2
[1] 1
[1] 0
But when I add 1 to the result D=1;for (j in 1:5){D=((D-1)%%4)+1;print(D)}
, it changes to:
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
Why does this happen?
This is what I would expect:
D=1;for (j in 1:5){D=(D-1)%%4;print(D+1)}
[1] 1
[1] 4
[1] 3
[1] 2
[1] 1
The code chunks above were written in a compressed form in order to avoid a lengthy post. A properly styled R code should look like this:
D <- 1
for (j in 1:5) {
D <- (D - 1) %% 4
print(D)
}
You initialize D
with 1. When j
is 0 and later, then you compute
D=((D-1)%%4)+1
therefore, when D
is 1, then the formula above will yield 1, independently of j's value, since D
only depends on its own previous value and whenever it was 1, the formula yields 1, hence D
will never change. Instead, try this formula:
D=(D%%4)+1
D
was 0, then the result will be 1D
was 1, then the result will be 2D
was 2, then the result will be 3D
was 3, then the result will be 4D
was 4, the result will be 1Since you want
[1] 1
[1] 4
[1] 3
[1] 2
[1] 1
you will need to initialize D
with 0, so the first result will be 1:
D=0;for (j in 1:5){D=(D%%4)+1;print(D)}
EDIT
The solution above provides 1 2 3 4 ... If, instead 1 4 3 2 1 ... is needed, then one can use (4-D)%%4 instead of D%%4 and initialize D with 2.