[R] inserting elements in a list

Jason Turner jasont at indigoindustrial.co.nz
Mon Feb 17 18:17:03 CET 2003


On Mon, Feb 17, 2003 at 02:01:47PM +0100, Agustin Lobo wrote:
...
> Let's say we have a vector:
> > a
> [1] "1" "2" "3" "5" "6" "3"
> 
> and we want to insert a "7" after
> any given "3", i.e., we want vector a 
> to become:
> 
> [1] "1" "2" "3" "7" "5" "6" "3" "7"
...

No one-step way I can think of.  I'd use a "for" loop.

a <- c(1,2,3,5,6,3)

N <- length(a)
for(ii in which(a==3)) {
    if(ii == N) {
        a <- c(a,7)
    } else {
        a <- c(a[1:ii],7,a[(ii+1):N])
    }
}

Cheers

Jason
-- 
Indigo Industrial Controls Ltd.
64-21-343-545
jasont at indigoindustrial.co.nz




More information about the R-help mailing list