Using for-Loop Index in R Programming (2 Examples)

In this article, I’ll illustrate how to identify and use a for-loop index in the R programming language.

Example 1: How to Get for-Loop Indices

for(my_index in 1:3) {                        # Run for-loop
  print(my_index)                             # Print index
}
# [1] 1
# [1] 2
# [1] 3

Example 2: Creating New Variable Based on for-Loop Index

for(my_index in 1:3) {                        # Starting for-loop
  variable_name <- paste0("var", my_index)    # Creating variable name using index
  assign(variable_name, my_index)             # Creating new variables
         
}
var1                                          # Printing new variables to console
# 1
var2
# 2
var3
# 3

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