R Errors Explained: Incorrect Number of Subscripts on Matrix

Error messages are going to occur from time to time, and they become more likely as programs get more complicated. The meaning of the “incorrect number of subscripts on matrix” error is not clear at first glance. One reason for this is the fact that it results from a very small mistake. This type of mistake is easy to make, but hard to find.

The circumstances of this error.

This error results from using a matrix notation on a data structure that is not a matrix. It is a surprisingly simple mistake to make, making and hard to find if you do not know what you’re looking for.

> x = rep(1, 10)
> for(i in 1:10){x[i,]=5}
Error in x[i, ] = 5 : incorrect number of subscripts on matrix

If you look closely at the “for loop” in the second line, you will see “i,” for the index of the vector”x” when it should be “i” for the index. The “i,” is used in a matrix as a catch-all index. This error message simply results from using the wrong notation.

What is causing this error?

The cause of this error message is applying matrix notation to vector. To show this to be true all that is needed is to remove the comma that denotes the matrix notation.

> x = rep(1, 10)
> for(i in 1:10){x[i]=5}

This example shows vector notation for the index you are using with the vector. When the notation “i,” is used, the program is looking for additional columns that do not exist in a vector. Because it cannot find those columns, it produces an error message to let you know that something is wrong. The error message is not easy to understand until you know what the problem is.

How to fix this error.

There are two ways of fixing this problem depending on the situation. The first situation is where you are working with a vector and accidentally include the coma. The second is where you are dealing with a matrix and you made some other mistake.

> x = rep(1, 10)
> for(i in 1:10){x[i]=5}

If you are dealing with a vector then you fix it by simply removing the comma. You would then be using the correct notation for a vector and the error goes away. This is simply a case of making sure that you are using the right notation for what you are doing.

> x=matrix(rep(0,100),nrow=10)
> for(i in 1:10){x[i,]=5}

The second solution is to make sure that the data structure you are referring to is actually a matrix. There are two ways that this mistake can occur. One is where the data structure was defined earlier in your program, and you thought that you had defined it as a matrix. The other is where you are using two similar object names and accidentally referred to the wrong one.