[R] inserting elements in a list
Ray Brownrigg
ray at mcs.vuw.ac.nz
Thu Feb 20 03:13:02 CET 2003
> From: Peter Wolf <pwolf at wiwi.uni-bielefeld.de>
>
> "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 <ray at mcs.vuw.ac.nz> http://www.mcs.vuw.ac.nz/~ray
More information about the R-help
mailing list