How to Write a for-Loop in R & RStudio (Example Code)
In this R tutorial you’ll learn how to apply for-loops.
Creation of Example Data
my_vec <- rep(1, 10) # Create example vector in R my_vec # Show example vector in RStudio console # 1 1 1 1 1 1 1 1 1 1 |
my_vec <- rep(1, 10) # Create example vector in R my_vec # Show example vector in RStudio console # 1 1 1 1 1 1 1 1 1 1
Example: Writing & Running for-Loop in R
for(index in 1:length(my_vec)) { # Define head of for-loop my_vec[index] <- my_vec[index] + index # Define body of for-loop } |
for(index in 1:length(my_vec)) { # Define head of for-loop my_vec[index] <- my_vec[index] + index # Define body of for-loop }
my_vec # Print results of for-loop # 2 3 4 5 6 7 8 9 10 11 |
my_vec # Print results of for-loop # 2 3 4 5 6 7 8 9 10 11