[R] Integer division

Göran Broström gb @end|ng |rom eh@r@@e
Mon Dec 19 14:22:00 CET 2022


I have a long vector x with five-digit codes where the first digit of 
each is of special interest, so I extracted them through

 > y <- x %/% 10000

but to my surprise y contained the value -1 in some places. It turned 
out that x contains -1 as a symbol for 'missing value' so in effect I 
found that

 > -1 %/% 10000 == -1

Had to check the help page for "%/%", and the first relevant comment I 
found was:

"Users are sometimes surprised by the value returned".

No surprise there. Further down:

‘%%’ indicates ‘x mod y’ (“x modulo y”) and ‘%/%’ indicates
      integer division.  It is guaranteed that

      ‘ x == (x %% y) + y * (x %/% y) ’ (up to rounding error)

I did expect  (a %/% b) to return round(a / b), like gfortran and gcc, 
but instead I get floor(a / b) in R. What is the reason for these 
different definitions? And shouldn't R's definition be documented?

Thanks, Göran



More information about the R-help mailing list