[R] inserting elements in a list

j+rhelp@howard.fm j+rhelp at howard.fm
Tue Feb 18 07:27:03 CET 2003

On 17 Feb 2003 20:11:11 +0100, "Peter Dalgaard BSA"
<p.dalgaard at biostat.ku.dk> said:
> Thomas Lumley <tlumley at u.washington.edu> writes:
> >   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.

Indeed they're not - and the code above fails to do this insertion:

> a[which(threes)+offset[threes]+1]<-7
> a
[1]  1  2  3  7  6  3 NA  7

The problem is that it is placing the '7's in the correct place, but is
not shifting the right-hand side of the list across to make room.

> 2) Show that the index in the last line is the same as
> which(threes)+seq(length=sum(threes))

That's a neat way to find the right spots to place the '7's - wherever
the '3's were before, plus one spot for each '3' that we've seen so
far... I'm not sure how to insert into the vector rather than replace
though - a quick browse through the list archives didn't turn up any
quick solutions (other than the types of loops suggested in earlier
answers in this thread).
  Jeremy Howard
  jhoward at fastmail.fm

More information about the R-help mailing list