Reputation: 296
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)
}
Upvotes: 4
Views: 80
Reputation: 76414
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.
Upvotes: 5
Reputation: 101014
You just need to add two more lines, say D <- D + 1
and D <- D - 1
like below
D <- 1
for (j in 1:5) {
D <- ((D - 1) %% 4)
D <- D + 1
print(D)
D <- D - 1
}
and you will obtain
[1] 1
[1] 4
[1] 3
[1] 2
[1] 1
Upvotes: 1
Reputation: 23
It returns you 1 every time because what you are doing is : D = 1
In your loop :
j = 1 : D = ((D - 1) %% 4 ) + 1
wich do D = ((1 - 1) %% 4 ) + 1
wich is equal to 0 %% 4 + 1 = 1
So at the end of this execution you get the same value of D as in the beginning and you do that 4 other times.
So your value of D doesn't change.
(English isn't my first language but if you need more details I would be happy to give you more)
Upvotes: 2