R Error: Subscript Out of Bounds (Example)


In this R tutorial you’ll learn how to fix the error message subscript out of bounds.

The article is structured as follows:

Let’s start right away.


Creating Example Data

First, we’ll have to create some example data:

my_mat <- matrix(1:20, ncol = 5)    # Create example matrix
my_mat                              # Print example matrix
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    5    9   13   17
# [2,]    2    6   10   14   18
# [3,]    3    7   11   15   19
# [4,]    4    8   12   16   20

Have a look at the previous output of the RStudio console. It shows that our example data is a numeric matrix consisting of four rows and five columns.


Example: Reproducing & Solving the Error: Subscript Out of Bounds

This Example shows the reason why the error message “subscript out of bounds” occurs.

Let’s assume that we want to extract certain rows or columns of our matrix. Then we could apply the following R code:

my_mat[3, ]                         # Printing third row of matrix
# [1]  3  7 11 15 19

As you can see in the previous output, we extracted the third row of our data set.

Now, let’s assume that we want to extract a row that doesn’t exist in our data (i.e. the 10th row):

my_mat[10, ]                        # Trying to print tenth row of matrix
# Error in my_mat[10, ] : subscript out of bounds

Then the R programming language returns the error message “subscript out of bounds”.

In other words: If you are receiving the error message “subscript out of bounds” you should check whether you are trying to use a data element that does not exist in your data.


Video, Further Resources & Summary

Do you need more info on the R codes of this tutorial? Then you could have a look at the following video which I have published on my YouTube channel. In the video, I show the R code of this tutorial:


The YouTube video will be added soon.


In addition, you might want to have a look at the other articles on my homepage.


On this page you learned how to solve the error subscript out of bounds in R programming. In case you have additional questions, let me know in the comments below. Furthermore, please subscribe to my email newsletter in order to receive updates on the newest articles.


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.