3 Easy Ways to Append Multiple Elements to a Vector in R

Vectors are the primary data type in R and can store multiple values of the same data type.

Vectors can store and manipulate data consistently and efficiently.

R append multiple elements to a vector

There are 3 easy ways to append multiple elements to a Vector in R.

  1. Using the c() function: The c() function combines multiple elements into a single vector.
  2. Using append() function: It appends multiple elements to the end of an existing vector.
  3. Using <<- operator: The <<- operator to append elements to the end of a vector.

Method 1: Using the c() function

The c() function combines multiple elements into a single vector in R.

rv <- c(11, 21, 46)

fv <- c(rv, 18, 19, 29)
cat("Appended Vector: ", fv, "\n")

Output

Appended Vector: 11 21 46 18 19 29

You can see that we appended multiple elements to the fv vector using the c() function. The fv vector is the combination of RV and other multiple elements.

Method 2: Using the append() function

The append() is a built-in function to add elements to the end of an existing vector. For example, define two vectors, combine vector elements in the final vector, and print it using the cat() function.

rv_1 <- c(11, 21, 46)
rv_2 <- c(18, 19, 29)

fv <- c(rv_1, rv_2)
cat("Appended Vector: ", fv, "\n")

Output

Appended Vector: 11 21 46 18 19 29

Method 3: Using the <<- operator

Using the <<- operator, we can append multiple elements at the end of a vector defined in the global environment.

rv_1 <- c(11, 21, 46)
rv_2 <- c(18, 19, 29)

fv <<- c(rv_1, rv_2)
cat("Appended Vector: ", fv, "\n")

Output

Appended Vector: 11 21 46 18 19 29

The <<- operator assigns a value to a variable in the global environment.

The <<- operator is similar to the <- operator, which is used to assign a value to a variable in the current environment, but the <<- operator allows you to assign a value to a variable that is defined in the global environment.

When using the <<- operator, you should use it cautiously because it can lead to unintended side effects if used carelessly.

Conclusion

To append multiple elements to a Vector in R, use either c() or append() function.

The c() and append() methods can append single or multiple elements to the Vector.

Further reading

How to append value to an empty list

R append to string

How to append an element to a list

Leave a Comment