> From: Peter Wolf <[EMAIL PROTECTED]>
> 
> "insert.values" <- function(x,pos.insert,x.insert){
> :

Which when reduced to its bare minimum to solve the stated problem,
becomes:
  threes <- which(a==3)
  a <- c(a, rep(7, length(threes)))[order(c(seq(a), threes))]

This is by far the overall fastest solution so far proposed, and
certainly is reasonably easy to understand.  However an even faster
solution is based on rep():

 N <- which(threes <- a == 3)           # which ones
 a <- rep(a, times = 1 + threes)        # duplicate them
 a[N + 1:length(N)] <- 7                # replace the duplicates

Relative timing for vector lengths n=1000 and n=10000 with 1000 repeats
(on a 1.7GHz P4 running R-1.6.1 under NetBSD) is as follows:

a <- sample(1:9, n, TRUE)                       n=1000  n=10000
lapply (Stephen Upton and Peter Dalgaard)         9.2s   117.8s
recursion (John Fox) [options(expressions=n)]    59.9s   stack overflow
offset <- (Thomas Lumley)                         1.4s   12.7s
offset <- (Peter Dalgaard)                        1.3s   10.9s
order() (Peter Wolf)                              1.1s    8.7s
rep() (me)                                        0.9s    7.6s

Hope this helps,
Ray Brownrigg <[EMAIL PROTECTED]>       http://www.mcs.vuw.ac.nz/~ray

______________________________________________
[EMAIL PROTECTED] mailing list
http://www.stat.math.ethz.ch/mailman/listinfo/r-help

Reply via email to