[R] Strange behaviour of as.integer()

Duncan Murdoch murdoch at stats.uwo.ca
Thu Jan 7 14:12:30 CET 2010


On 07/01/2010 7:31 AM, Ulrich Keller wrote:
> I have encountered a strange behaviour of as.integer() which does not
> seem correct to me. Sorry if this is just an indication of me not
> understanding floating point arithmetic.
> 
>> .57 * 100
> [1] 57
>> .29 * 100
> [1] 29
> 
> So far, so good. But:
> 
>> as.integer(.57 * 100)
> [1] 56
>> as.integer(.29 * 100)
> [1] 28
> 
> Then again:
> 
>> all.equal(.57 * 100, as.integer(57))
> [1] TRUE
>> all.equal(.29 * 100, as.integer(29))
> [1] TRUE
> 
> This behaviour is the same in R 2.10.1 (Ubuntu and Windows) and 2.9.2
> (Windows),
> all 32 bit versions. Is this really intended?

Yes, as the man page states, non-integer values are truncated towards 
zero.  Normal printing rounds them.  So .57*100, which is slightly less 
than 57, is rounded to 57 for printing, but is truncated to 56 by 
as.integer.

 > .57*100 < 57
[1] TRUE

Duncan Murdoch



More information about the R-help mailing list