[R] inserting elements in a list
tlumley at u.washington.edu
Tue Feb 18 16:49:03 CET 2003
On Tue, 18 Feb 2003 j+rhelp at howard.fm wrote:
> 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 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.
The code does work, but you have to use all of it, not just that line.
The *previous* line does the shifting.
More information about the R-help