[R] fast value replacement in (numeric) vector

Stefan Evert stefan.evert at uos.de
Sat Sep 20 23:48:59 CEST 2008


On 20 Sep 2008, at 23:41, Ling, Gary (Electronic Trading) wrote:

> Hi R users,
> What is the fastest way to replace a(some) value(s) in a (numeric)
> vector?
> I checked ?replace, but its output is another vector.
> 1) I wonder if there's any function to perform in-place replacement?

How about

L[n] <- 0

which also works with index/value vectors:

L[c(0,n)] <- c(1,0)

> 2) Or any other function would do what I'm looking for with faster
> speed?

 > system.time(replicate(500, L <- replace(L,n,0)))
    user  system elapsed
   1.027   1.179   2.203

 > system.time(replicate(500, L[n] <- 0))
    user  system elapsed
   0.508   0.552   1.054

I suppose that's the fastest you can get because of R's copy-on-write  
semantics (if I understand the R internals correctly, it's always a  
bit magical to me ...)



Best regards,
Stefan Evert

[ stefan.evert at uos.de | http://purl.org/stefan.evert ]



More information about the R-help mailing list