[R] The elegant way to test if a number is a whole number

Marc Schwartz marc_schwartz at me.com
Thu Sep 8 20:48:15 CEST 2011


There was a post from Martin Maechler some years ago and I had to search a bit to find it. For these sorts of issues, I typically trust his judgement.

The post is here:

  https://stat.ethz.ch/pipermail/r-help/2003-April/032471.html

His solution also handles complex numbers.

HTH,

Marc Schwartz

On Sep 8, 2011, at 1:37 PM, Bert Gunter wrote:

> Have a close look at ?storage.mode and ?typeof.
> 
> The problem here, as usual and as you seem to allude is: define
> "integer" . Mathematically, there is an unequivocal definition, but
> not so in finite precision arithmetic. Are you referring to the
> machine representation (typeof()), or the approximate value. And if
> the latter, how approximate?
> 
> I think both your solution and its perceived "beauty" will depend on
> your exact definition and context.
> 
> You may receive wiser advice. If so, please ignore mine.
> 
> Cheers,
> 
> Bert
> 
> On Thu, Sep 8, 2011 at 11:27 AM, Alexander Engelhardt
> <alex at chaotic-neutral.de> wrote:
>> Hi,
>> 
>>    x <- 0.2*5
>>    is.integer(x)
>> 
>> gives me FALSE because R stores it as a float number, right?
>> Is there an elegant way to work around that problem? Right now
>> I'm using
>> 
>>    x <- 0.2*5
>>    round(x) == x
>> 
>> which returns TRUE. But more strictly I should use all.equal(),
>> right?
>> 
>> I somehow just don't like the--pardon--ugliness of those pieces
>> of code. Maybe there is a beautiful way to write that. If not,
>> no big problem -- I just like beautiful code :-)
>> 
>> Cheers,
>>  Alex
>> 
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>> 
> 
> 
> 
> -- 
> "Men by nature long to get on to the ultimate truths, and will often
> be impatient with elementary studies or fight shy of them. If it were
> possible to reach the ultimate truths without the elementary studies
> usually prefixed to them, these would not be preparatory studies but
> superfluous diversions."
> 
> -- Maimonides (1135-1204)
> 
> Bert Gunter
> Genentech Nonclinical Biostatistics
> 467-7374
> http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list