[R] fast value replacement in (numeric) vector

Ling, Gary (Electronic Trading) Gary_Ling at ml.com
Sat Sep 20 23:41:14 CEST 2008


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? 
2) Or any other function would do what I'm looking for with faster
speed?

# here is something I tried in R:
n <- 100000
L <- 1:n
system.time(replicate(500, L <- c(0,L[-1])))
system.time(replicate(500, L <- c(L[-n],0)))
system.time(replicate(500, L <- replace(L,1,0)))
system.time(replicate(500, L <- replace(L,n,0)))


### result
> system.time(replicate(500, L <- c(0,L[-1])))
   user  system elapsed 
  1.514   1.260   2.773 
> system.time(replicate(500, L <- c(L[-n],0)))
   user  system elapsed 
  1.477   1.284   2.762 
> system.time(replicate(500, L <- replace(L,1,0)))
   user  system elapsed 
  0.981   0.930   1.911 
> system.time(replicate(500, L <- replace(L,n,0)))
   user  system elapsed 
  0.936   0.973   1.909 

I look forward to hear your opinion.
Thanks in advance,
Gary
--------------------------------------------------------

This message w/attachments (message) may be privileged, confidential or proprietary, and if you are not an intended recipient, please notify the sender, do not use or share it and delete it. Unless specifically indicated, this message is not an offer to sell or a solicitation of any investment products or other financial product or service, an official confirmation of any transaction, or an official statement of Merrill Lynch. Subject to applicable law, Merrill Lynch may monitor, review and retain e-communications (EC) traveling through its networks/systems. The laws of the country of each sender/recipient may impact the handling of EC, and EC may be archived, supervised and produced in countries other than the country in which you are located. This message cannot be guaranteed to be secure or error-free. This message is subject to terms available at the following link: http://www.ml.com/e-communications_terms/. By messaging with Merrill Lynch you consent to the foregoing.



More information about the R-help mailing list