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
xis a vector.valueswill be appended tox.afteris an optional parameter.valueswill be added or appended toxafter a length provided asafter. The default value ofafterislength(x), which means by defaultvalueswill be appended afterx.
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().
