[R] converting numeric to integer

Thomas Mang thomas.mang at fiwi.at
Sat May 16 20:49:40 CEST 2009


Suppose I have x, which is a variable of class numeric. The calculations 
performed to yield x imply that mathematically it should be an integer , 
but due to round-off errors, it might not be (and so in either 
direction). The error is however small, so round(x) will yield the 
appropriate integer value. Moreover, this integer values is guaranteed 
to be representable by an 'integer' class, that is -2^31 < x < 2^31, and 
logically it is an integer anyway. So I want to convert x from class 
'numeric' to 'integer'. What is the most elegant, but always correct 
way, to achieve this conversion ?

What comes to mind is of course something along:

x = as.integer(round(x))

I am, however, not sure if this always works, because I do not know if 
the round-function is guaranteed to return a numeric value which, in 
finite binary representation, is always >= the underlying mathematical 
integer. If that is however guaranteed, that would of course be a simple 
+ elegant one.

An alternative I came up with is:

x = as.integer(round(x) + ifelse(x >= 0, 0.5, -0.5))
Where I explicitly add a bit to ensure the finite binary representation 
must be >= the underlying integer, and then truncate the decimal digits.
IMO, this one is always guaranteed to work, at least within the 
numerical range of what integers are limited to anyway.

What's your opinion on the issue ?
Any other solution ?

Thanks a lot in advance and cheers,

More information about the R-help mailing list