Home » How to Append Values to a Vector Using a Loop in R

How to Append Values to a Vector Using a Loop in R

by Erma Khan

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

for(i in 1:10) {
  data 

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 

#use for loop to add integers from 1 to 10 to vector 
for(i in 1:10) {
  data #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 

#use for loop to add square root of integers from 1 to 10 to vector 
for(i in 1:10) {
  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 #define new data to add
new 
#use for loop to append new data to vector
for(i in 1:length(new)) {
  data #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 #append the value "19" to the end of the vector
new #display resulting vector
new

[1] 4 5 12 19

You can find more R tutorials on this page.

Related Posts