How to Fix in R: incorrect number of subscripts on matrix


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.

Instead, we simply need to remove the comma:

#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.

Additional Resources

How to Fix in R: NAs Introduced by Coercion
How to Fix in R: Subscript out of bounds
How to Fix Error in R: incorrect number of dimensions

Leave a Reply

Your email address will not be published. Required fields are marked *