[R] inserting elements in a list

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


On Mon, Feb 17, 2003 at 06:32:45PM +0100, Peter Dalgaard BSA wrote:
> 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.
...
> This should work:
> 
> unlist(lapply(a,function(x)if(x==3)c(3,7)else x))
> 
> Whether it is cleaner is debatable.

Looks much cleaner to me.

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




More information about the R-help mailing list