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 ifx
contains integer numbers! For that, useround
, as in the functionis.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