Skip to content
Back to formatted view

Raw Message

Message-ID: <41A2038C.5080002@lancaster.ac.uk>
Date: 2004-11-22T15:19:40Z
From: Barry Rowlingson
Subject: How to insert one element into a vector?
In-Reply-To: <8975119BCD0AC5419D61A9CF1A923E95E898C7@iahce2knas1.iah.bbsrc.reserved>

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)]))
}

  > v=c(1,2,3,4,6)

  > insert(v,5,5)
  [1] 1 2 3 4 5 6

Yay.

  > insert(v,5,1)
  [1] 1 5 1 2 3 4 6

Oops.

  Cant be bothered to fix it, the principle is there.

Baz