[R] converting numeric to integer

Gabor Grothendieck ggrothendieck at gmail.com
Sun May 17 11:54:48 CEST 2009


as.integer(x + 0.5)

assuming the calculation error is less than 0.5 .

On Sat, May 16, 2009 at 2:49 PM, Thomas Mang <thomas.mang at fiwi.at> wrote:
> Hello,
> 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,
> Thomas
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list