[R] How to insert one element into a vector?
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Mon Nov 22 16:36:41 CET 2004
Barry Rowlingson <B.Rowlingson at lancaster.ac.uk> writes:
> michael watson (IAH-C) wrote:
> > There must be a million ways of doing this!
>
> Actually I'd say there were no ways of doing this, since I dont
> think you can actually insert into a vector - you have to create a new
> vector that produces the illusion of insertion!
>
> Here's a Q+D function that fails if you try and insert at the start,
> or at the end. Its very D.
>
> insert <- function(v,e,pos){
> return(c(v[1:(pos-1)],e,v[(pos):length(v)]))
> }
This is actually an exercise in a certain introductory book on R, with
the intention of having the student do the obvious c(v[1:4],5,v[5:5])
style computation and maybe think a little about the edge effects. I
only recently saw the somewhat unfortunately named append() function,
which has been in S/R ever since the blue book...:
> append(v,5,4)
[1] 1 2 3 4 5 6
--
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