Select Page

How to Solve R Error: Incorrect number of dimensions

by | Programming, R, Tips

This error occurs when you try to subset an object outside its number of dimensions. We can get the number of dimensions of an object using the dim() function. We can then solve the error by ensuring we only subset using the available dimensions.

This tutorial will go through the error in detail with code examples.

Table of contents


Let’s look at an example to reproduce the error. First, we will define a numeric vector with 8 values:

x<-c(1, 7, 10, 13, 22, 25, 14, 19)

Next, we will try to access the first row and the second column using the subset operator.

x[ , 2]

Let’s run the code to see what happens:

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

The error occurs because we are attempting to subset using two dimensions. We can check the dimensions of an object using the dim() function. For example,


The dim() function returns null because a vector has a length but not other dimensions.


We can solve the error by subsetting with one dimension. Let’s look at how to access the fifth element in the vector:

[1] 22

Using a colon, we can access several values in the vector, also called a slice. Let’s look at how to access the elements at index 2 through to 5.

[1]  7 10 13 22


Congratulations on reading to the end of this tutorial!

For further reading on R-related errors, go to the articles: 

Go to the online courses page on R to learn more about coding in R for data science and machine learning.

Have fun and happy researching!