[R] How %% and %/% work on negative numbers?

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Thu Apr 24 15:03:09 CEST 2003


Kenneth Cabrera wrote:

> I mean why you obtain different results if you work on C or anywhere 
> else and in R?

  Because R is not C, and they are doing different things.

> -17 mod 15 should be -2, but R shows 13 and
> -17 integer division 15 should be -1, but R shows -2
> because the reconstruction formula should be 15*(-1)+(-2) == -17
> Or am I wrong?

  R is doing "arithmetic modulo N" (which can only take values from 0 to 
N-1) and C is doing 'remainder when divided by N' which can be negative.

  These are two different (but related) things. R's %% operator is 
documented as "x mod y" - which means it does modulo-y arithmetic. The 
man page for 'fmod' in C says: "The  fmod()  function  computes  the 
remainder of dividing x by y". I dont have my K+R C book handy to see 
how they define the x % y operator, but I suspect its the same.

Baz



More information about the R-help mailing list