[R] Is.integer and testing for integers

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Jun 30 18:40:49 CEST 2005


That allows values just bigger than an integer but not just less than an 
integer.  Also, since .Machine$double.eps is a relative tolerance, there 
are no non-integers greater than one meeting the criterion, and the
only non-integers it lets through are like

> is.int(c(1e-20, -1e-20))
[1]  TRUE FALSE

Since integers a lot bigger than allowed by as.integer can be expressed 
exactly as reals, the best suggestion appears to be

(x == round(x))

> x <- 2^c(30, 50, 200)
> x == as.integer(x)
[1] TRUE   NA   NA
Warning message:
NAs introduced by coercion
> x == round(x)
[1] TRUE TRUE TRUE


On Thu, 30 Jun 2005, Sundar Dorai-Raj wrote:

>
>
> Tuszynski, Jaroslaw W. wrote:
>>  Hi,
>>
>> I was trying to figure out if there is a function in R that tests if R
>> object contains only integers. I though "is.integer" would be it, but this
>> function only checks "whether its argument is of integer type or not". As a
>> result
>> 	x = (1:5)^2
>> 	is.integer(x)
>> Returns false. Of course I can write my own function like
>> "!any(x!=as.integer(x))" but I am just trying to make sure I am not
>> reinventing the wheel.
>>
>> Jarek
>
> Since "^" returns a double, it's no wonder is.integer(x) didn't work as
> you expected. Perhaps you want something more like
>
> is.int <- function(x, tol = .Machine$double.eps) {
>   (x - floor(x)) < tol
> }
> is.int((1:5)^2)

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list