R for-Loop Only Returns Last Value of Output (Example Code)

In this tutorial, I’ll illustrate how to return the entire output of a for-loop in the R programming language.

Example: for-Loop Only Returns Last Output Value – How to Fix?

for(index in 1:10) {                  # Head of for-loop
  my_output <- index                  # Store results
}
my_output                             # Returning output
# 10
my_output <- numeric()                # Creating empty numeric vector
for(index in 1:10) {                  # Head of for-loop
  my_output <- c(my_output, index)    # Store results in vector
}
my_output                             # Returning output
#  [1]  1  2  3  4  5  6  7  8  9 10

Leave a Reply

Your email address will not be published.

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

Menu
Top