+5 votes
in Programming Languages by (72.7k points)
I want to add a new element to the start position of a vector. What R function should I use to insert an element at a given position?

1 Answer

+2 votes
by (354k points)
selected by
 
Best answer

The append() function can be used to add elements to a vector.

The format of the function is as follows:

append(x, values, after = length(x))

where, x= the vector the values are to be appended to, values= new elements that need to be added, and after= a subscript, after which the values are to be appended.

If you want to add an element at the start of the vector, you need to use after=0.

To add one element at the start:

> f <- c(11:15)
> append(f, 5, after = 0)
[1]  5 11 12 13 14 15

To add multiple elements at the start:

> append(f, 6:10, after = 0)
 [1]  6  7  8  9 10 11 12 13 14 15

To add multiple elements at a given position

> append(f, 16:20, after = 4)
 [1] 11 12 13 14 16 17 18 19 20 15

Related questions

+5 votes
1 answer
+4 votes
1 answer

...