for-Loop Only Returns Last Value in R (2 Examples)

 

In this tutorial, I’ll illustrate how to return not only the last value of a for-loop in the R programming language.

The post consists of this content:

You’re here for the answer, so let’s get straight to the exemplifying R syntax.

 

Example 1: Why for-Loop Only Returns Last Value

Example 1 shows the problem: Why is a for-loop only returning the output of the last iteration? Have a look at the following R code:

for(i in 1:5) {         # Example for-loop
  out <- i^2
}

As you can see based on the following output of the RStudio console, we created a data object containing only the value created by the last iteration of the loop:

out                     # Print output
# 25

Next, I’ll show how to fix this issue…

 

Example 2: Save for-Loop Output of Each Iteration in Vector

This Example illustrates how to save the entire output of a for-loop in a vector object. First, we have to create an empty vector, in which we will store the output of our for-loop later on:

out <- numeric()        # Create empty vector

Now, we can append the output of each for-loop iteration to this vector using the c() function in R:

for(i in 1:5) {         # Example for-loop
  out <- c(out, i^2)
}

Let’s have a look at our output:

out                     # Print output
# 1  4  9 16 25

Looks good!

 

Video & Further Resources

If you need further explanations on the R programming code of this article, you could watch the following video of my YouTube channel. I explain the R syntax of this tutorial in the video.

 

The YouTube video will be added soon.

 

Furthermore, you might read the other posts of this homepage.

 

In summary: In this R programming post you learned how to return the entire output of a for-loop. If you have additional questions, please tell me about it in the comments below.

 

Subscribe to my free statistics newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Menu
Top