Append to Vector in Loop in R (Example) | Add Value in while- & for-Loops

 

In this tutorial you’ll learn how to add new vector elements in a for-loop in the R programming language.

Table of contents:

Let’s take a look at some R codes in action.

 

Creation of Example Data

Let’s first create some example data:

my_vec <- 1:5                       # Create example vector
my_vec                              # Print example vector
# 1 2 3 4 5

As you can see based on the previous output of the RStudio console, our example data is a numeric vector ranging from 1 to 5.

 

Example: Adding New Elements to Vector in for-Loop

In this Section, I’ll show how to append new vector elements to our original vector in a for-loop.

The following for-loop has three iterations and in each iteration we are creating a new vector element and we are concatenating this element to our vector:

for(i in 1:3) {                     # Head of for-loop
  new_value <- i * (- 1)            # Creating new value
  my_vec <- c(my_vec, new_value)    # Appending new value to vector
}

Let’s have a look at our new vector in the RStudio console:

my_vec                              # Returning final vector
# 1  2  3  4  5 -1 -2 -3

As you can see, we added three new values to our vector. Note that we could use a similar R code in case we would like to append new vector elements in a while-loop or in a repeat-loop.

 

Video & Further Resources

Do you want to learn more about loops in R? Then I can recommend to watch the following video of my YouTube channel. In the video, I explain the topics of this tutorial in RStudio.

 

The YouTube video will be added soon.

 

In addition, I can recommend to read the other articles of this website.

 

In this R tutorial you learned how to concatenate additional elements to a vector in a loop. If you have additional comments and/or questions, let me know in the comments section. Furthermore, please subscribe to my email newsletter to get updates on new articles.

 

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