Try this: as.integer(x + sign(x) * .5)
On Sun, May 17, 2009 at 6:01 AM, Thomas Mang <thomas.m...@fiwi.at> wrote: > Hi, > > The problem is, x might be negative. If x == -6.9999999, the result should > be -7, not -6. That's why my original proposal had the ifelse-condition (one > could alternatively write sign(x) * 0.5, BTW. > I agree however that in my proposal, the round(x) is redundant, one can use > x itself as left-hand argument for the sum operation. Is there however still > a more 'elegant' way ? > > thanks, > Thomas > > > > Gabor Grothendieck wrote: >> >> Try: >> >> 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.m...@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@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. >>> >> > > ______________________________________________ R-help@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.