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 Vector

First, we have to create some data through which we can loop in the examples later on:

my_vec <- letters[1:5]                   # Create example vector
my_vec                                   # Print example vector
# [1] "a" "b" "c" "d" "e"

As you can see, we have created a vector object containing five character elements.


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 this task, we first have to initialize an index counter:

loop_index_1 <- 0                        # Create index count

Next, we can run a for-loop using our example data and the index counter as shown below:

for(i in my_vec) {                       # Run for-loop
  loop_index_1 <- loop_index_1 + 1
  print(loop_index_1)                    # 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.

As in Example 1, we first have to create an index count:

loop_index_2 <- 0                        # Create index count

Next, we can create variables dynamically using this index count within a for-loop:

for(i in my_vec) {                       # Run for-loop
  loop_index_2 <- loop_index_2 + 1
  assign(paste0("variable_",             # Create variables

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

variable_1                               # Return new variables
# 1
# 4
# 9
# 16
# 25


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.

2 Comments. Leave new

  • Example 1: Print for-Loop Index to Console
    is wrong, you are not printing the index, but the value, try a random vector and you will get its contents, rather the loop index


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.