[R] A random insertion position in a vector

Ray Brownrigg Ray.Brownrigg at mcs.vuw.ac.nz
Fri Jun 14 04:16:56 CEST 2002


Douglas Bates asks:
> The part that took us the longest time was deciding how to insert the
> offspring cell into the array in a way that doesn't break down at the
> boundaries.
> 
> iterate <-
>     function(current)
> {
>     ## Update the array of cells with a birth followed by a death
>     parent <- sample(seq(along = current), 1)  # index of the parent
>     pos <- parent - sample(c(0,1), 1)          
>     newcell <- ## generate the new cell based on the type of the parent
>     newvec <- insert(current, newcell, pos)
>     newvec[-sample(seq(along = newvec), 1)]
> }
> 
> Can anyone come up with a cleaner way of doing the insertion or
> perhaps the complete birth/death step?
> 
Here's a minor modification which avoids the separate function call to
insert().  One might say it is a little more elegant, using order to
insert the new element, but it does use slightly more CPU time (a few
%, but this is dependent on how complex the new cell generation is):

iterate <-
function(current)
{
    ## Update the array of cells with a birth followed by a death
    index <- seq(along = current)
    parent <- sample(index, 1)  # index of the parent
    pos <- parent + sample(c(0.5, -0.5), 1)          
    newcell <- ## generate the new cell based on the type of the parent
    newvec <- c(current, newcell)[order(c(index, pos))]
    newvec[-sample(seq(along = newvec), 1)]
}

Hope this helps,
Ray Brownrigg <ray at mcs.vuw.ac.nz>	http://www.mcs.vuw.ac.nz/~ray
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list