Check if the number is integer

Roman Luštrik picture Roman Luštrik · Aug 13, 2010 · Viewed 128k times · Source

I was surprised to learn that R doesn't come with a handy function to check if the number is integer.

is.integer(66) # FALSE

The help files warns:

is.integer(x) does not test if x contains integer numbers! For that, use round, as in the function is.wholenumber(x) in the examples.

The example has this custom function as a "workaround"

is.wholenumber <- function(x, tol = .Machine$double.eps^0.5)  abs(x - round(x)) < tol
is.wholenumber(1) # is TRUE

If I would have to write a function to check for integers, assuming I hadn't read the above comments, I would write a function that would go something along the lines of

check.integer <- function(x) {
    x == round(x)
}

Where would my approach fail? What would be your work around if you were in my hypothetical shoes?

Answer

James picture James · Aug 13, 2010

Another alternative is to check the fractional part:

x%%1==0

or, if you want to check within a certain tolerance:

min(abs(c(x%%1, x%%1-1))) < tol