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

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
}
my_vec                                      # Print results of for-loop
# 2  3  4  5  6  7  8  9 10 11

Leave a Reply

Your email address will not be published.

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