[R] Ceiling to the nearest ten?
Barry Rowlingson
b.rowlingson at lancaster.ac.uk
Mon Jan 14 18:47:37 CET 2008
Rob Robinson wrote:
> Perhaps not the most elegant but 10*ceiling(x/10) usually works for me...
I thought maybe adding five and rounding to the nearest -1 decimal
places might be quicker:
> round(a+5,-1)
[1] 10 10 20 20 20 30 30 40 40 40
gives same as:
> ceiling(a/10)*10
[1] 10 10 20 20 20 30 30 40 40 40
but it's not quicker:
> system.time(for(i in 1:1000000){round(a+5,-1)})
[1] 17.505 0.116 19.538 0.000 0.000
> system.time(for(i in 1:1000000){ceiling(a/10)*10})
[1] 5.212 0.048 5.726 0.000 0.000
which surprised me, given that the ceiling example has a multiply and a
divide to do before working out the ceiling, whereas the round just has
an add to do before working out the rounding, and I can't immediately
see why ceilinging should be faster than roundinging:
> system.time(for(i in 1:1000000){ceiling(a)})
[1] 2.724 0.044 3.053 0.000 0.000
> system.time(for(i in 1:1000000){round(a)})
[1] 12.397 0.092 14.339 0.000 0.000
but maybe if I think about it a bit more I'll see...
Barry
More information about the R-help
mailing list