How to Append Multiple Elements to a Vector in R

There are the following methods to append multiple elements to a Vector in R.

  1. Using the “c()” function
  2. Using the “append()” function
  3. Using <<- operator

Method 1: Using the c() function

The c() is a built-in function that 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.

Leave a Comment