R – Append Vector

append() adds element(s) to a vector.

Syntax of append()

The syntax of append() method is:

</>
Copy
 append(x, values, after = length(x))

where

  • x is a vector.
  • values will be appended to x.
  • after is an optional parameter. values will be added or appended to x after a length provided as after. The default value of after is length(x), which means by default values will be appended after x.

append() does not modify the vector x or values, but returns the resulting vector.

Append elements to a Vector

In the following example, we will take a vector and append elements to it using append().

</>
Copy
> x = c('Max', 'Jack', 'Carl')
> x = append(x, 'Mike')
> print (x)
[1] "Max"  "Jack" "Carl" "Mike"

Concatenate Two Vectors

You can concatenate two vectors using append. For values argument, pass the vector you would like to concatenate to x.

</>
Copy
> x = c('Max', 'Jack', 'Carl')
> values = c('Mike', 'Samanta')
> y = append(x, values)
> print (y)
[1] "Max"     "Jack"    "Carl"    "Mike"    "Samanta"

append() returns the resulting concatenated vector of x and values.

Append a Vector after a specific Length of First Vector

We can use after argument of append() to insert the values vector after a specific length in x vector.

</>
Copy
> x = c('Max', 'Jack', 'Carl')
> values = c('Mike', 'Samanta')
> y = append(x, values, 2)
> print (y)
[1] "Max"     "Jack"    "Mike"    "Samanta" "Carl"

In the above example, values vector is inserted in x after 2nd element.

Conclusion

In this R Tutorial, we learned how to append element(s) or a vector to another vector using append().