[R] Bug in rep() function

Sarah Goslee sarah.goslee at gmail.com
Mon Sep 15 18:32:49 CEST 2014


No, actually you've discovered FAQ 7.31.

> a <- (1-0.9)*100
> a
[1] 10
> print(a, digits=20)
[1] 9.9999999999999982236

In combination with the description in ?rep:
     Non-integer values of ‘times’ will be truncated towards zero.  If
     ‘times’ is a computed quantity it is prudent to add a small fuzz.

you get 9 times.

The best thing to do is ensure that your values are integer *before*
passing them to rep(), unless you know that truncating toward zero is
the right thing to do.

Sarah

On Mon, Sep 15, 2014 at 11:30 AM, Samuel Knapp <samuel.k at gmx.de> wrote:
> Dear all,
>
> I have discovered a bug in the standard rep() function: At certain values,
> rep() does not replicate the element by the proper number of times:
>
>> a <- (1-0.9)*100
>> a
> [1] 10
>> length(rep(1,times=a))
> [1] 9
>> length(rep(1,each=a))
> [1] 9
>
> As shown, this happens as well for the times= as for the each= parameter. It
> does not depend on the kind of element that is to be repeated:
>
>> length(rep("abc",each=a))
> [1] 9
>
> I tried to narrow down the bug, but haven't really managed to find a pattern
> behind the bug. Here is a list with values for a (see above) that returns a
> false object ( after the value for a, i've collected the expected length and
> the length that is produced by r):
>
> # mistake at
> (1-0.9)*100       10           9
> (1-0.8)*100       20          19
> (1-0.8)*1000      200       199
> (1-0.9)*1000      100       99
> (1-0.9)*10            1         0
> (1-0.8)*10            2         1
> (1-0.9)*1000000000      100000000       99999999
> (2-1-0.9)*100         10      9
> (10/10-0.9)*100     10      9
>
> # the following sets for a work fine
> (1+0.1)*100
> (1-0.1)*100
> (1-0.7)*100
> (1-0.99)*1000
> (1-0.7)*10
> (1-0.90)*10
> (1-0.95)*100
> (1-0.95)*1000
> (2-0.9)*1000
> (2-1.9)*100
> (1.1-1)*100
> (10-9)*100
>
> Did I make any mistake? Or where else should I address this problem?
>
> Thanks and best regards,
> Samuel
>

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



More information about the R-help mailing list