How to Fix in R: incorrect number of dimensions
Last Updated :
18 Mar, 2022
In this article, we will discuss how we can fix the “incorrect number of dimensions” error in R Programming Language.
One common error that one may face in R is:
Error in [x, 10] : incorrect number of dimensions
The R compiler produces such an error when one tries to refer to an object by providing more dimensions than the actual dimension the object has.
Reproducing the error:
Let us consider an example in which we have a vector initialized with 5 values in it.
R
myVector <- c (10,13,2,6,12)
|
As you can see in the snippet that myVector is a one-dimensional vector having 5 values in it. Now suppose we mistakenly try to subset it with two dimensions:
Example:
In this program, we are accessing the value stored at the 4th row and the 1st column.
R
myVector <- c (10, 13, 2, 6, 12)
myVector[4, ]
|
Output:
Output
Example:
In this program, we are accessing the value stored at the 1st row and the 4th column. And here the R compiler produces this error because we are trying to subset with 2-dimensions while the vector has 1-dimension.
R
myVector <- c (10, 13, 2, 6, 12)
myVector[, 4]
|
Output:
Output
How to fix this error:
We can fix this error easily by subsetting with one dimension.
Example:
Consider a program in which we are accessing the fifth value of the vector (Treating as 1-dimension data structure).
R
myVector <- c (10, 13, 2, 6, 12)
myVector[5]
|
Output:
Output
Note: A large number of contiguous values of the vector can also be accessed with subset by one dimension:
Example:
In this program, we are accessing elements using one-dimension subset values from position equal to 2 to the position equal to 5 (inclusive).
R
myVector <- c (10, 13, 2, 6, 12)
myVector[2:5]
|
Output:
Output
Share your thoughts in the comments
Please Login to comment...