[R] inserting elements in a list

John Fox jfox at mcmaster.ca
Mon Feb 17 23:05:03 CET 2003


Dear Peter, Thomas, et al.,

In the spirit of programming exercises, here's a recursive solution:

insert.values <- function(vector, after, values){
     where <- which(vector == after)[1]
     if (is.na(where)) vector
     else c(vector[1:where], values,
         Recall(vector[-(1:where)], after, values))
     }
insert.values(a, "3", "7")

Regards,
  John

At 08:11 PM 2/17/2003 +0100, Peter Dalgaard BSA wrote:
>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))

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------




More information about the R-help mailing list