How do I Append Values to a Vector Using a Loop in R?

Appending values to a vector using a loop in R is a relatively simple task that can be accomplished using the append() function. This function takes two arguments, the vector and the value to be appended. Within a loop, this function can be used to sequentially add values to the vector by passing the vector name as the first argument and the value to be added as the second argument. This allows for the efficient accumulation of values into a vector without having to manually create a new vector each time.


To append values to a vector using a loop in R, you can use the following basic syntax:

for(i in 1:10) {
  data <- c(data, i)
}

The following examples show how to use this syntax in practice.

Example 1: Append Values to Empty Vector

The following code shows how to append values to an empty vector in R:

#define empty vector
data <- c()

#use for loop to add integers from 1 to 10 to vector 
for(i in 1:10) {
  data <- c(data, i)
}

#view resulting vector
data

[1]  1  2  3  4  5  6  7  8  9 10

Example 2: Perform Operation & Append Values to Vector

The following code shows how to perform an operation and append values to an empty vector:

#define empty vector
data <- c()

#use for loop to add square root of integers from 1 to 10 to vector 
for(i in 1:10) {
  data <- c(data, sqrt(i))
}

#view resulting vector
data
[1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751 2.828427
[9] 3.000000 3.162278

Example 3: Append Values to Existing Vector

The following code shows how to append values to an existing vector in R:

#define vector of data
data <- c(4, 5, 12)

#define new data to add
new <- c(16, 16, 17, 18)

#use for loop to append new data to vector
for(i in 1:length(new)) {
  data <- c(data, new[i])
}

#view resulting vector
data

[1] 4 5 12 16 16 17 18

Example 4: Append a Single Value to Vector

If you simply want to append a single value to the end of an existing vector, you can use the following code without a for loop:

#define vector of data
data <- c(4, 5, 12)

#append the value "19" to the end of the vector
new <- c(data, 19)

#display resulting vector
new

[1] 4 5 12 19

You can find more R tutorials on .

x