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

Example

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,

dim(x)
NULL

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

Solution

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

x[5]
[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.

x[2:5]
[1]  7 10 13 22

Summary

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!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee