How to check if each element in a vector is integer or not in R?

integer, r, vector

Solution

The simplest (and fastest!) thing is probably this:

stopifnot( all(y == floor(y)) )

...So trying it out:

y <- c(3,4,9)
stopifnot( all(y == floor(y)) ) # OK

y <- c(3,4.01,9)
stopifnot( all(y == floor(y)) ) # ERROR!

If you want a better error message:

y <- c(3, 9, NaN)
if (!isTRUE(all(y == floor(y)))) stop("'y' must only contain integer values")

Problem

Say, I have a vector y, and I want to check if each element in y is integer or not, and if not, stop with an error message. I tried is.integer(y), but it does not work.

Original source