for-Loop Index in R (2 Examples)


In this R tutorial you’ll learn how to use for-loop indices.

Table of contents:

Let’s start right away:


Example 1: Print for-Loop Index to Console

This Example explains how to return the current for-loop index to the RStudio console using the print function in R.

for(i in 1:5) {                          # Run for-loop
  print(i)                               # Print index
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5

As you can see based on the previous RStudio console output, we used the print function to identify the index of each for-loop iteration.


Example 2: Using for-Loop Index to Name Variables

The indices of for-loops can also be used to create or name variables dynamically. In the following R code, we use the assign and paste0 functions to create new data objects:

for(i in 1:3) {                          # Run for-loop
  assign(paste0("variable_", i), i^2)    # Create variables

Let’s print our new variables to the RStudio console:

variable_1                               # Return new variables
# 1
# 4
# 9


Video & Further Resources

Have a look at the following video of my YouTube channel. I show the contents of this article in the video.


The YouTube video will be added soon.


Furthermore, you might read the related tutorials of I have released several posts already:


Summary: In this R programming tutorial you learned how to identify and use a for-loop index. In case you have any further questions, please let me know in the comments below.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

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.