[R] inserting elements in a list

Thomas Lumley tlumley at u.washington.edu
Mon Feb 17 19:39:03 CET 2003


On 17 Feb 2003, Peter Dalgaard BSA wrote:

>
> > 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"
> > ...
> >
> >
> This should work:
>
> unlist(lapply(a,function(x)if(x==3)c(3,7)else x))
>
> Whether it is cleaner is debatable.
>

Or
  N<-length(a)
  threes<- a==3
  offset<- c(0,cumsum(threes)[-N])
  a[offset+(1:N)]<-a
  a[which(threes)+offset[threes]+1]<-7

for a more vectorised version.  Equally ugly, but understanding
these two solutions is probably educational.

Adding elements in the middle is something vectors are not good at, in
contrast to (pair-based or linked) lists.

	-thomas




More information about the R-help mailing list