"%%" and "%/%" for the remainder and the quotient

R

R Problem Overview


I am wondering how and why the operator %% and %/% are for the remainder and the quotient.

Is there any reason or history that R developer had given them the meaning they have?

 > 0 %/% 10
[1] 0
> 30 %% 10
[1] 0
> 35 %/% 10
[1] 3
> 35 %% 10
[1] 5

R Solutions


Solution 1 - R

In R, you can assign your own operators using %[characters]%. A trivial example:

'%p%' <- function(x, y){x^2 + y}

2 %p% 3 # result: 7

While I agree with BlueTrin that %% is pretty standard, I have a suspicion %/% may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/% means do a special sort of division (integer division)

Solution 2 - R

Have a look at the examples below for a clearer understanding of the differences between the different operators:

> # Floating Division:
> 5/2
[1] 2.5
> 
> # Integer Division:
> 5%/%2
[1] 2
> 
> # Remainder:
> 5%%2
[1] 1

Solution 3 - R

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKH KimView Question on Stackoverflow
Solution 1 - REdwardView Answer on Stackoverflow
Solution 2 - Rsync11View Answer on Stackoverflow
Solution 3 - RBlueTrinView Answer on Stackoverflow