# Modulo Operations In R

I had a discussion with a co-worker the other day about whether the modulo operation always has the same rank in order of operations as multiplication and division.  My comment was that in C-based languages and SQL, this is generally true, but it isn’t always the case with all programming languages.  Case in point, here’s how R handles various scenarios:

• 9*3%%5 = 27.  In this case, modulo happens before multiplication, so it becomes 9*3.
• (9*3)%%5 = 2.  I want to show that operations in parentheses happen before operations outside parentheses, just like you would expect in math.
• 9*(3%%5) = 27.  Again, operations in parentheses happen first.
• 24/6%%5 = 24.  Like with multiplication, modulo happens before division, so it becomes (24/1).
• (24/6)%%5 = 4.  The operation becomes 4%%5, which is 4.
• 24/(6%%5) = 24.  This becomes 24/1, which is 24.

By contrast, with SQL, 9*3%5 = 2 and 24/6%5 = 4.  This means that modulo operations are handled at the same level as multiplication and division, whereas with R, modulo operations are handled before multiplication and division.

So how about exponents?  Surely exponents resolve before modulo, right?

• 3**5%%3 = 0
• (3**5)%%3 = 0
• 3**(5%%3) = 9

So yes, exponents resolve before modulo.