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

David Winsemius dwinsemius at comcast.net
Thu Sep 8 21:42:54 CEST 2011


On Sep 8, 2011, at 3:35 PM, Alexander Engelhardt wrote:

> Am 08.09.2011 20:48, schrieb Marc Schwartz:
> > 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.
>
> For those too lazy to follow
> He is basically creating the function is.whole:
>
>    is.whole <- function(x)
>      is.numeric(x) && floor(x)==x

Are you sure? I thought the test would have been all.equal(x, round(x, 
0) )

My reasoning was that 1.999999999999 should be considered 2 but floor  
would make it 1.

 > x=1.999999999999
 > x
[1] 2
 > floor(x)
[1] 1
 > isTRUE(all.equal(x, floor(x)))
[1] FALSE
 > all.equal(x, round(x,0))
[1] TRUE


>
> Seems like the most appropriate way now. I'll make it so!
> Thanks for your help :-)
> -- 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list