rmoduloarithmetic-expressions

R - Addition after modulo operation


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

Edit:

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)
}

Solution

  • 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
    

    Since 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.