R Errors Explained: subscript out of bounds r

While error messages are an unfortunate part of computer programming, they are a problem you will run into as your programs become more complex. This is because as a program becomes more complex the greater the likelihood that you will forget the little details. The “subscript out of bounds” error message is a fairly straightforward one to fix once you know what you are looking for. It is basically an index overflow error for a matrix.

The circumstances of this error.

This error message occurs when you input an index into a matrix that is too large for that matrix. In a simple program, it is unlikely to occur but in more complex programs there are several ways that can occur by accident.

> x = matrix(0,5,7)
> for(i in 1:6)
+ {x[i,i] = 1}
Error in `[=`(`*tmp*`, i, i, value = 1) : subscript out of bounds

Here, we have an example of a for-loop for incrementally accessing locations in the matrix “X”, and it goes further than the bounds of the matrix. This is the most common type of situation in which this error is likely to occur. It can happen just because you forget the size of the matrix.

What is causing this error?

The cause of this error is quite simple and easy to fix. It results from trying to access an index number that is out of the range of a matrix.

> x = matrix(0,5,7)
> x[6,6]
Error in x[6, 6] : subscript out of bounds

This is an extremely simple example and one you should never make in actual practice. In this case, it is a deliberate setup to illustrate the error message. Looking at this bit of code, you will see that “x” is a 5 X 7 matrix. However, the second line calls position 6,6 which is too big for the first index, and so the subscript is out of bounds.

How to fix this error.

Fixing this error message is simply a matter of making sure that you never try to access an index for a matrix that is out of range

> x = matrix(0,5,7)
> for(i in 1:5)
+ {x[i,i] = 1}

Note how in this example the for-loop end at 5 rather than 6 and as a result does not go out of bounds. One way to prevent this from happening is to use the nrow() and ncol() functions for any for-loop indexing the rows or columns respectively.

> x = matrix(0,5,7)
> for(i in 1:nrow(x))
+ { for(j in 1:ncol(x))
+ {x[i,j] = 1}}

This simple piece of code is an example of this type of fix for the for-loop situation. Ultimately, the key to fixing this problem is making sure that any value you use to index a matrix, remains inside the bounds of the matrix. The nrow() and ncol() functions are also a good way to check the validity of a value before accessing any part of a matrix.

Scroll to top