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

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

One error you may encounter in R is:

`Error in x[i, ] `

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 ```

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, ] ```

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