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 |
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 |
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