Check if the number is integer

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?


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

Here's a solution using simpler functions and no hacks:

all.equal(a, as.integer(a))

What's more, you can test a whole vector at once, if you wish. Here's a function:

testInteger <- function(x){
  test <- all.equal(x, as.integer(x), check.attributes = FALSE)
  if(test == TRUE){ return(TRUE) }
  else { return(FALSE) }
}

You can change it to use *apply in the case of vectors, matrices, etc.