test for integers in R

as.integer(x, ...)
integer(length = 0)
is.integer(x)

integer creates a integer vector of the specified length. Each element of the vector is equal to 0.

as.integer attempts to coerce its argument to be of integer type. The answer will be NA unless the coercion succeeds.

is.integer returns TRUE or FALSE depending on whether its argument is of integer type or not,

The weird thing I find when I am trying to use is.integer is, is.integer(3) will return false.

so what happens?

because

Becaues is.integer shows the internal representation, which is not an
integer but a double (real number). Some functions create integer vectors,
for example the : notation:

> is.integer(1:10) [1] TRUE

Or, is.integer(as.integer(3)) will also return TURE

Note:  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:

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

To test if a R object contains only integers:

!any(x!=as.integer(x))

Reference:

http://127.0.0.1:30947/library/base/html/integer.html

http://tolstoy.newcastle.edu.au/R/help/05/07/7671.html

https://stat.ethz.ch/pipermail/r-help/2006-January/086797.html


		
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s