[R] inserting elements in a list

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Mon Feb 17 20:14:03 CET 2003


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.

Extra exercises for the over-achievers:

1) Show that 

offset <- cumsum(threes) - threes

also works.

2) Show that the index in the last line is the same as

which(threes)+seq(length=sum(threes))

-- 
   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