[R] 1 not equal to 1, and rep command

Sarah Goslee sarah.goslee at gmail.com
Mon Sep 12 18:46:04 CEST 2011


Not so strange, in fact this is FAQ 7.31, and has to do (as you guess)
with the way that computers store numbers.

You need to do as you did, and use round() or floor() or similar to
ensure that you get the results you expect.

Sarah

2011/9/12 Benjamin Høyer <bdhoyer at gmail.com>:
> Hi
>
> I need to use rep() to get a vector out, but I have spotted something very
> strange.  See the reproducible example below.
>
> N <- 79
> seg <- 5
> segN <- N / seg   # = 15.8
>
> d1 <- seg - ( segN - floor(segN) ) * seg
> d1                    # = 1
>
> rep(2, d1)          # = numeric(0), strange - why doesn't it print one "2"?
> rep(2, 1)            # 2, ok
> rep(2, d1 / 1,1)   # 2, this does work
> rep(2, d1 + 2)    # "2 2" - also works but...
> d1 + 2              # = 3! so why does it print two 2s above?
>
> d1 == 1             # FALSE
> all.equal(d1, 1)   # TRUE
> identical(d1, 1)   # FALSE
>
> Try something else...
>
> d2 <- 4 - ( (79/4) - floor(79/4))* 4
> d2                     # = 1
>
> rep(2, d2)          # 2 : this works!
>
> d2 == 1             # TRUE
> all.equal(d2, 1)   # TRUE
> identical(d2, 1)   # TRUE
>
> #version info
> platform       x86_64-pc-linux-gnu
> arch           x86_64
> os             linux-gnu
> system         x86_64, linux-gnu
> status
> major          2
> minor          10.1
> year           2009
> month          12
> day            14
> svn rev        50720
> language       R
> version.string R version 2.10.1 (2009-12-14)
>
>
> Seems like there's some binary maths errors here somewhere.  Very strange to
> me.  Anyway, I need to be able to use the result d1 in a rep() command.  Any
> way to force rep not to be *too* specific in how it reads its "times"
> argument?
>
> Thanks in advance,
> Benjamin Hoyer
>



-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list