How can I append values to a vector using a loop in R?

Appending values to a vector using a loop in R refers to the process of adding new elements to a pre-existing vector in a sequential manner. This can be achieved by using a loop, which allows for the repeated execution of a set of instructions until a specific condition is met. By using a loop, one can efficiently add multiple values to a vector without having to manually input each value. This enables the user to easily manipulate and expand the vector, making it a useful tool in data analysis and programming tasks in R.

Append Values to a Vector Using a Loop in R


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