Home » How to Fix Error in R: incorrect number of dimensions

How to Fix Error in R: incorrect number of dimensions

by Tutor Aspire

One error you may encounter in R is:

Error in x[, 3] : incorrect number of dimensions

This error occurs when you attempt to subset some object in R by more dimensions than the object has.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

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

#define vector
x 

The vector is one-dimensional, but suppose we attempt to subset by two dimensions:

#attempt to access value in first row and third column
x[ , 3]

Error in x[, 3] : incorrect number of dimensions

#attempt to access value in third row and first column
x[3, ]

Error in x[3, ] : incorrect number of dimensions

We receive an error because we attempted to subset by two dimensions when the vector only has one dimension.

How to Fix the Error

The easiest way to fix this error is to simply subset by one dimension. For example, here’s how to access the third value in the vector:

#access third value in vector
x[3]

[1] 7

We can also access several values in the vector at once. For example, here’s how to access the values in positions 2 through 5 in the vector:

#access values in positions 2 through 5
x[2:5]

[1]  4  7  7 14

Since we subset by only one dimension, we avoid the incorrect number of dimensions error.

Additional Resources

How to Fix in R: NAs Introduced by Coercion
How to Fix in R: Subscript out of bounds
How to Fix in R: longer object length is not a multiple of shorter object length
How to Fix in R: number of items to replace is not a multiple of replacement length

You may also like