Learn R Online
 Home            

R append to vector

In this article you will learn how to append to a vector in R programming also called vector merging or adding values. How to append a single value, a series, or another vector at the beginning, end or at any desired position in a given vector.

Syntax of R append

append to vector in R programming

append() function is used to add elements to a given vector. This function takes atleast two arguments and atmost three arguments. Lets see the syntax

append(vector, data, after)

1. append() is the function which will add elements to a vector.

2. vector is the first argument. It is the vector in which values are going to be added. This argument is necessary.

3. data is the data, value or values, vector to be added in the vector(first argument) of append function. This argument is also needed for append.

4. after is the subscript after which values are to be appended. 

If you are an absolute beginner in R and want to learn R for data analysis or data science from R experts I will strongly suggest you to see this R for Absolute Beginners Course

R append Example:

Append single value to vector:

If you want to add one value 6 at the end of a given vector a, then the R code will be

> a <- c(1,2,3,4,5)

> append(a,6)
[1] 1 2 3 4 5 6

Here a is a vector consisting of five values and we append 6 at the end of it. 

Similarly, another example

> x <- c(letters[1:5])
> x
[1] "a" "b" "c" "d" "e"
> y <- append(x,letters[6:10])
> y
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

Append vector to a vector:

If you want to add a vector y to x

> x <- c(1:4)
> y <- c(5:8)

> append(x,y)
[1] 1 2 3 4 5 6 7 8

Write the first vector and then the vector which is to be appended. Here x is the first vector which consists of four numbers 1,2,3,4 and y is the second vector consisting 5,6,7,8. Now y is added to x by simply writing append(x,y)

Append at a specific location:

If a value or a vector is to be added in a given vector at a specific location then the third argument "after" is used. It is simply the subscript after which values are to be added. If you want to add after the first value in list, use 1 as argument, if you want to add after the second value, use 2 as argument and so on.

> i <- c('a','f')
> i
[1] "a" "f"
> append(i, letters[2:5],1)
[1] "a" "b" "c" "d" "e" "f"

See another example

> s <- c(1:5)
> append(s,20:23,2)
[1]  1  2 20 21 22 23  3  4  5

The first vector s contains numbers from 1 to 5. Four values from 20 to 23 are added after the second value in s.