How to Create a For Loop in R and Append Results to a Vector

Creating a for loop in R and appending results to a vector

One common procedure you may want to perform in R is using a for loop to repeat some process several times, then appending the results of the process to a vector. This tutorial explains how to do so using two different examples. 

For Loop Example – Numeric Vector

The following example shows how to create a loop that picks a random number between 1 and 10, 20 times, then appends each number to a numeric vector.

#create an empty numeric vector
num_vector <- numeric()

#create a loop that picks a random number between 1 and 10, 20 times. 
#Append each result to the numeric vector defined above.
for(i in 1:20) {

#generate random number between 1 and 10
number <- runif(1, 1, 10)

#append this random number to the i-th position in the vector
num_vector[i] <- number
}

#view vector of 20 random numbers
num_vector

# [1] 6.537753 3.008067 4.979126 4.444119 3.786783 7.159006 2.369399 5.344314
# [9] 1.161575 6.197420 9.658708 3.666595 1.691599 3.053068 9.825492 5.015388
#[17] 5.534652 5.362132 9.935340 1.593897

For Loop Example – Character Vector

The following example shows how to create a loop that picks a random character from the alphabet 20 times, then appends each number to a character vector.

#create an empty character vector
char_vector <- character()

#create a loop that picks a random character from the alphabet 20 times. 
#Append each character to the character vector defined above.
for(i in 1:20) {

#select random character
charac <- sample(letters, 1)

#append this random character to the i-th position in the vector
char_vector[i] <- charac
}

#view vector of 20 random characters 
char_vector

# [1] "o" "f" "z" "x" "f" "k" "f" "i" "z" "i" "e" "a" "m" "j" "x" "x" "y" "q" "z"
#[20] "g"

Leave a Reply

Your email address will not be published. Required fields are marked *