How to for-Loop Over Vector Elements in R (Example Code)

In this article you’ll learn how to loop over the elements of a vector object in the R programming language.

Example Data

x <- 10:20                         # Creating example vector
x                                  # Returning vector to RStudio console
#  [1] 10 11 12 13 14 15 16 17 18 19 20

Example: for-Looping Through Vector

for(index in 1:length(x)) {        # Start of loop
  
  my_output <- x[index]^2          # Generating some output values
  
  print(my_output)                 # Returning output values
}
# [1] 100
# [1] 121
# [1] 144
# [1] 169
# [1] 196
# [1] 225
# [1] 256
# [1] 289
# [1] 324
# [1] 361
# [1] 400

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.
You need to agree with the terms to proceed

Menu
Top