Store Results of Loop in Vector in R (Example) | Save Output of for-Loop in Array

 

In this R tutorial you’ll learn how to save the output of a for-loop in a vector or array.

The article contains the following contents:

Here’s how to do it.

 

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

In this Example, I’ll show how to store the results of a for-loop in a vector (or array) in R.

We first have to create an empty vector. The following for-loop will produce character outputs, for that reason, we are creating an empty character vector:

my_vec <- character()            # Create empty character vector
my_vec                           # Print vector to RStudio console
# character(0)

The following for-loop contains three parts: A head were we specify the iterations of our loop; A line of code were we are creating some output; And a line of code were we are storing the output in a vector object.

for(i in 1:5) {                  # Head of for-loop
  my_out <- LETTERS[i]           # Create some output
  my_vec <- c(my_vec, my_out)    # Save output in vector
}

Let’s have a look at the final result:

my_vec                           # Show final vector
# "A" "B" "C" "D" "E"

As you can see based on the previous output of the RStudio console, the previous for-loop has created a vector consisting of five character elements. Note that we could apply the same type of R code within a repeat-loop or within a while-loop as well.

 

Video & Further Resources

Would you like to learn more about vectors and loops? Then you might have a look at the following video of my YouTube channel. I’m showing the examples of this article in the video:

 

The YouTube video will be added soon.

 

In addition, you could read some of the other articles on my website.

 

In summary: You learned in this article how to store loop results in a vector in R. If you have further questions, please tell me about it in the comments section.

 

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