Fix in R: incorrect number of subscripts on matrix?

Fixing incorrect number of subscripts on matrix in R involves ensuring that the number of rows and columns in the matrix are equal, and that each element of the matrix is being addressed correctly in terms of its row and column location. The matrix can be addressed in R using the “[row, column]” notation, which can be used to identify and assign each element in the matrix. After ensuring that the matrix has the correct number of rows and columns, and that each element is being addressed correctly, the matrix can then be manipulated as desired.


One error you may encounter in R is:

Error in x[i, ] <- 0 : incorrect number of subscripts on matrix

This error occurs when you attempt to assign some value to a position in a vector, but accidently include a comma as if you were assigning some value to a row and column position in a matrix.

This tutorial shares exactly how to fix this error.

Example 1: Fix Error for a Single Value

Suppose we have the following vector in R with 5 values:

#define vector
x <- c(4, 6, 7, 7, 15)

Now suppose we attempt to assign the value ’22’ to the third element in the vector:

#attempt to assign the value '22' to element in third position
x[3, ] <- 22

Error in x[3, ] <- 22 : incorrect number of subscripts on matrix

We receive an error because we included a comma when attempting to assign the new value.

Instead, we simply need to remove the comma:

assign the value '22' to element in third position
x[3] <- 22

#display updated vector
x

[1]  4  6 22  7 15

Example 2: Fix Error in a for Loop

This error can also occur when we attempt to replace several values in a vector using a ‘for’ loop.

For example, the following code attempts to replace every value in a vector with a zero:

#define vector
x <- c(4, 6, 7, 7, 15)

#attempt to replace every value in vector with zero
for(i in 1:length(x)) {
    x[i, ]=0
  }

Error in x[i, ] = 0 : incorrect number of subscripts on matrix

We receive an error because we included a comma when attempting to assign the zeros.

#define vector
x <- c(4, 6, 7, 7, 15)

#replace every value in vector with zero
for(i in 1:length(x)) {
    x[i]=0
  }

#view updated vector
x

[1] 0 0 0 0 0

Once we remove the comma, the code runs without errors.

x