R Save Results of Loop in Vector (Example Code)

In this tutorial you’ll learn how to store loop results in a vector in the R programming language.

Example: Saving Output of for-Loop in Vector or Array

x <- numeric()              # Empty numeric vector
for(index in 1:10) {        # Start of for-loop
  out_now <- index^2        # Creating some output
  x <- c(x, out_now)        # Appending result to vector
x                           # Returning resulting vector to console
#  [1]   1   4   9  16  25  36  49  64  81 100

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed