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