Loop Through Vector in R (Example) | Run while- & for-Loops Over Vectors

 

This tutorial shows how to loop over the elements of a vector object in R programming.

The post looks as follows:

Let’s get started.

 

Example Data

First, we’ll have to create some data that we can use in the examples below:

vec <- c(6, 3, 9, 0, 6, 5)        # Create example vector
vec                               # Print example vector
# 6 3 9 0 6 5

Have a look at the previously shown output of the RStudio console. It shows that our exemplifying vector consists of six numeric vector elements.

 

Example: Looping Over Vector Elements Using for-Loop

This Example illustrates how to write and run a for-loop over vector elements in R. Within the body of the loop, we are creating some output and we are printing this output to the RStudio console:

for(i in 1:length(vec)) {         # Head of for-loop
  out <- vec[i] + 10              # Create some output
  print(out)                      # Print output to console
}
# [1] 16
# [1] 13
# [1] 19
# [1] 10
# [1] 16
# [1] 15

Note that we could apply a similar R syntax to while-loops or repeat-loops as well.

 

Video & Further Resources

If you need more info on the topics of this post, you may have a look at the following video of my YouTube channel. In the video, I’m explaining the R programming code of this article in a programming session.

 

The YouTube video will be added soon.

 

In addition, you might want to read the other tutorials of this website. I have released several other articles already.

 

In this article you learned how to use a for-loop to loop through vectors or arrays in R. Please let me know in the comments section, in case you have further questions.

 

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