[R] function to compare numbers
Sarah Goslee
sarah.goslee at gmail.com
Fri Sep 3 15:54:40 CEST 2010
You could potentially use sign()
> sign(3 - 5)
[1] -1
> sign(5 - 3)
[1] 1
> sign(5 - 5)
[1] 0
But... this could fail when you think two numbers are equal and the
computer doesn't, due to floating point precision. (Your version could
fail in exactly the same way.)
> x <- .3 - .2
> x
[1] 0.1
> sign(x - .1)
[1] -1
So how you implement this will depend on what you need it for. Something
like this should work, if you choose the appropriate level of precision:
> sign(round(x - .1, 9))
[1] 0
Sarah
On Fri, Sep 3, 2010 at 9:33 AM, Hyunchul Kim <hyunchul.kim.sfc at gmail.com> wrote:
> Hi, all
>
> is there a built-in function to compare two numbers?
>
> something like following function
>
> cmp <- function(x, y){
> value <- 0
> if (x > y){
> value <- 1
> }else if (x == y){
> value <- 0
> }else {
> value <- -1
> }
> return(value)
> }
>
> Thanks in advance,
>
> Hyunchul
>
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list