Skip to content

How to insert one element into a vector?

7 messages · michael watson (IAH-C), Deepayan Sarkar, Peter Dalgaard +3 more

#
There must be a million ways of doing this!
If you want to keep the order:

v <- c(1,2,3,4,6)
sort(c(v,5))

Mick

-----Original Message-----
From: jing tang [mailto:tang_chalmers at hotmail.com] 
Sent: 22 November 2004 14:44
To: r-help at stat.math.ethz.ch
Subject: [R] How to insert one element into a vector?


suppose I want to insert 5 into the vector (1,2,3,4,6) between 4 and 6.
thx!

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html
#
michael watson (IAH-C) wrote:
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
#
On Monday 22 November 2004 09:19, Barry Rowlingson wrote:
Pretty much what 'append' does.

Deepayan
#
Barry Rowlingson <B.Rowlingson at lancaster.ac.uk> writes:
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...:
[1] 1 2 3 4 5 6
#
Deepayan Sarkar wrote:

            
A shame then, that help.search("insert") doesn't find 'append'! I cant 
think why anyone looking for a way of _inserting_ a value in the middle 
of a vector would think of looking at "append"!

  Python has separate insert and append methods for vectors.

  >>> x=[1,2,3,4,6]
  >>> x.insert(4,5)
  >>> x
  [1, 2, 3, 4, 5, 6]
  >>> x.append(99)
  >>> x
  [1, 2, 3, 4, 5, 6, 99]


Barry
#
On Mon, 22 Nov 2004, Barry Rowlingson wrote:

            
Yes, this should be fixed.
I don't think this is a good idea unless there are efficiency issues. 
You could always define one: the definition is fairly simple.
    insert<-append

 	-thomas
#
On Mon, 2004-11-22 at 17:43, Barry Rowlingson wrote:
So has R. R's 'insert' is called 'append', and R's 'append' is called
'c'. Counter-intuitively though, and I'm happy that Peter Dalgaard
didn't know that 'append' inserts: it gives some hope to us ordinary
mortals.

cheers, jazza