[R] inserting elements in a list

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Mon Feb 17 18:32:02 CET 2003


Jason Turner <jasont at indigoindustrial.co.nz> writes:

> 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])
>     }
> }

This should work:

unlist(lapply(a,function(x)if(x==3)c(3,7)else x))

Whether it is cleaner is debatable.

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list