[R] inserting elements in a list

Stephen Upton upton9265 at yahoo.com
Mon Feb 17 14:49:02 CET 2003


Agustin,

Not sure this is the most effective means, but works:
> a
[1] 1 2 3 5 6 3
> lapply(as.list(a), function(x) if(x==3) x<-c(3,7)
else x) -> aa
> aa
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3 7

[[4]]
[1] 5

[[5]]
[1] 6

[[6]]
[1] 3 7

> unlist(aa)
[1] 1 2 3 7 5 6 3 7
>
Basically, convert vector to a list, modify that
element of the
list
matching your condition, then unlist the resulting
list.

HTH
steve


Agustin Lobo wrote:

> I've searched the doc for insert
> and could not find the way to do the following,
> hope someone can help:
>
> 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"
>
> That is, how can we replce one
> element by more than one elements?
> (...causing the vector to go beyond its
> length)
>
> Thanks
>
> Agus
>
> Dr. Agustin Lobo
> Instituto de Ciencias de la Tierra (CSIC)
> Lluis Sole Sabaris s/n
> 08028 Barcelona SPAIN
> tel 34 93409 5410
> fax 34 93411 0012
> alobo at ija.csic.es
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help




More information about the R-help mailing list