How to Add or Append Elements to a Vector in R

To add or append elements to a Vector in R, you can use the “append()” method.

Syntax

append(x, value, index(optional))

Parameters

  1. x: It is the vector to which values are appended.
  2. value: The value that needs to be added in the modified vector.
  3. index: It is a subscript, after which the values are to be appended.

Return Value

The append() method returns a vector containing the values in x with the elements of values appended after the specified element of x.

Example 1: Add Element to Vector using append()

The append() is a built-in method that adds the various integer values into a Vector in the last position.

data <- 4:8

cat(data, "\n")

modified_data <- append(data, 11)

cat("After appending an element to a vector", "\n")

cat(modified_data)

Output

4 5 6 7 8
After appending an element to a vector
4 5 6 7 8 11

We appended the “11″ element to a data vector at the end of the vector. This is because the append() method adds the element at the end of a Vector.

Example 2: Appending an element using the c() function

The “c()” is a built-in R function that can add an element to the existing vector or initiate a new Vector. The c() function combines data into a vector or a list.

v1 <- 4:8
v2 <- 11

data <- c(v1, v2)

cat(data)

Output

4 5 6 7 8 11

And it appends an element at the end of the vector.

Example 3: Appending multiple elements to the Vector

To append multiple elements to a Vector in R, you can use the “append()” method and pass the vector to the existing vector. It will spread out in the existing vector and add multiple elements.

v1 <- 4:8
v2 <- 9:11

cat("Before appending elements to v1", "\n")

cat(v1, "\n")

modified_data <- append(v1, v2)

cat("After appending multiple elements to a v1", "\n")

cat(modified_data)

Output

Before appending elements to v1
4 5 6 7 8

After appending multiple elements to a v1
4 5 6 7 8 9 10 11

We add multiple elements to the existing vector by appending a new vector of all our elements.

Example 4: Adding element at the specific position in Vector

To append an element at the specific position in Vector, “pass the index parameter to the append() function”. The index is an optional parameter that can add an element after the index.

v1 <- 4:8
v2 <- 11

cat("Before adding element to v1", "\n")

cat(v1, "\n")

cat("Appending element after index 2", "\n")

modified_data <- append(v1, v2, 2)

cat(modified_data)

Output

Before adding element to v1
4 5 6 7 8
Appending element after index 2
4 5 11 6 7 8

You can see that we added an element “11” after index 2 of the vector.

Example 5: Append a value to an empty vector

You can use the “c()” function to append elements to an empty vector in R.

rv <- character()

rv2 <- c(rv, "K", "L")
print(rv2)

Output

[1] "K" "L"

Conclusion

To add or append single or multiple elements to a vector in R, you can use either the “append()” or “c()” function.

Leave a Comment