R – Append Element(s) to Vector
In this tutorial, we will learn how to append one or more elements to vector in R programming Language.
To append one or more elements to a vector in R, call append()
function and pass the vector and the element(s) to it as arguments.
Syntax
The syntax to append element(s) to vector x
is
append(x, values, after = length(x))
where
Parameter | Description |
---|---|
x | [Mandatory] Vector to which element(s) has to be appended. |
values | [Mandatory] Element(s) that are appended. |
after | [Optional] The position after which the element(s) are appended. |
append()
does not modify the original vector, but creates and returns a new vector with the elements of original vector appended with given values. So, if we want to update the original vector, we have assign the returned value of the function to the original vector itself.
Examples
Append an Element to a Vector
In this example, we take a vector x
with three elements, and append an element to it using append()
function.
Example.R
x <- c(2, 4, 6)
x <- append(x, 8)
print(x)
Output
[1] 2 4 6 8
Append Multiple Elements to a Vector
In this example, we will append four elements to the vector x
.
Example.R
x <- c(2, 4, 6)
values <- c(8, 10, 12, 14)
x <- append(x, values)
print(x)
Output
[1] 2 4 6 8 10 12 14
Conclusion
In this R Tutorial, we learned how to append one or more elements to a vector in R, with the help of example programs.