Search code examples
rfactors

R: Calculate factors of a number in R


I was playing with R a little bit and I came out with this behavior that I don't understand:

num <- seq(1,20,1)

num[num %% c(1,2) == 0]
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

So it seems to be an analog expression of

num[num %% 1 == 0 | num %% 2 == 0]

But when I do the following gets weird:

num[num %% c(1,3) == 0]
[1]  1  3  5  6  7  9 11 12 13 15 17 18 19

num[num %% c(1,4) == 0] 
[1]  1  3  4  5  7  8  9 11 12 13 15 16 17 19 20

I have been thinking about it, but I can't come out with an explanation for this. It's just out of curiosity, but if someone has a reason it would be very interesting to hear!.

Thanks!


Solution

  • As jogo says, it's the recycling rule.

    The result of num %% 1 is

    [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

    whilst the result of num %% 3 is

    [1] 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2

    Looking at the result of num %% c(1,3)

    [1] 0 2 0 1 0 0 0 2 0 1 0 0 0 2 0 1 0 0 0 2

    The first number in the result is taken from the first number of the num %% 1 result, the second from the second number of the num %% 3 result, the third from the third in num %% 1 and so on.