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

Jason Morgan jwm-r-help at skepsi.net
Thu Sep 8 20:36:14 CEST 2011


Hello Alex,

Have you tried the modulus operator?

> 2 %% 1
[1] 0
> 2.1 %% 1
[1] 0.1

~Jason

On 2011.09.08 20:27:14, Alexander Engelhardt 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.

-- 
Jason W. Morgan
Ph.D. Candidate
Department of Political Science
*The Ohio State University*
154 North Oval Mall
Columbus, Ohio 43210



More information about the R-help mailing list