[R] how to judge a virable is a integer?

S Ellison S.Ellison at LGCGroup.com
Mon Oct 20 15:01:05 CEST 2014


> It's due to that, 1 is a numeric, 1.2 is a numeric, though it's true. but deeply,
> when i want to know 1 is an integer,  there seems no easy way to get the
> answer.
> So, is there anyone happen to know it?

First, you are not being as clear as you may think when you say " when i want to know 1 is an integer". It isn't. 1L is an integer. 1 is floating point. Do you want to know whether something is _stored as_ integer (eg 2L), whether it is a floating point number with exactly no nonzero digits after the point (eg 2.0), or whether it is something which would normally be expected to be integer if represented to infinite precision but is not exactly represented because of finite machine precision (eg sqrt(2)^2)?

Once you've sorted out which of those you want - I think the last of the three - please read the posts you’re replying to. all.equal() was the suggested answer and is likely to be the nearest to a reliable answer you will get. Almost anything else will at least sometimes fail; for example

sqrt(4.0) == 2L
# [1] TRUE

#But 
sqrt(2)^2 == 2L
#[1] FALSE

#whereas 
all.equal(sqrt(2)^2, 2L)
#[1] TRUE

Thus, all.equal can be used to test for something that would normally be considered an integer within machine precision, for example using
nearly.integer <- function(x) all.equal(x, round(x))

You may make the comparison closer to a 'within machine precision' comparison  by amending the tol argument to all.equal, which is documented on the help page you were referred to.

S Ellison




*******************************************************************
This email and any attachments are confidential. Any use, copying or
disclosure other than by the intended recipient is unauthorised. If 
you have received this message in error, please notify the sender 
immediately via +44(0)20 8943 7000 or notify postmaster at lgcgroup.com 
and delete this message and any copies from your computer and network. 
LGC Limited. Registered in England 2991879. 
Registered office: Queens Road, Teddington, Middlesex, TW11 0LY, UK


More information about the R-help mailing list