How To Fix R Error Message: incorrect number of dimensions

Error messages are an annoying but important part of programming. These messages tell you when there is a problem. Unfortunately, they are not always helpful in telling you exactly what the problem is. The “incorrect number of dimensions” error message is one of these because you can get it even when the dimensions in your code are right.

The circumstances of this error.

This error message occurs when trying to add the contents of a data frame into an array. What is confusing about this error message is that it only occurs when you try to retrieve the contents of the array.

> df = read.table(text = ‘
+ A B C
+ 1 3 20 81
+ 2 4 34 13
+ 3 5 46 18
+ 4 6 42 16
+ 5 7 65 26
+ 6 8 71 28
+ 7 9 79 31′, header=TRUE)
>
> Ar = array(dim=c(7,3,10))
>
> Ar[,,1] = df
> Ar[,,1]
Error in Ar[, , 1] : incorrect number of dimensions

At first glance, it looks like the problem may be that the first two subscripts are missing. One reason that this is not the case is that the same format is used to add that data frame to the array. It only occurs when you try to access it again.

> Ar[1,1,1]
Error in Ar[1, 1, 1] : incorrect number of dimensions

The error message still occurs, when you are using all of the subscripts. This shows that the problem is not with the earlier omission of specific subscripts.

How to fix this error.

This error occurs by trying to equate a part of the matrix to a data frame. The error occurs because this process does not work right. Fixing this error only requires not trying to transfer the data in bulk. The solution is to use nested for-loops to transfer the data one segment at a time.

> df = read.table(text = ‘
+ A B C
+ 1 3 20 81
+ 2 4 34 13
+ 3 5 46 18
+ 4 6 42 16
+ 5 7 65 26
+ 6 8 71 28
+ 7 9 79 31′, header=TRUE)
>
> Ar = array(dim=c(7,3,10))
>
> for (i in 1:7){
+ for (ii in 1:3){
+ Ar[i,ii,1] = df[i,ii]
+ }
+ }
>
> Ar[,,1]
[,1] [,2] [,3]
[1,] 3 20 81
[2,] 4 34 13
[3,] 5 46 18
[4,] 6 42 16
[5,] 7 65 26
[6,] 8 71 28
[7,] 9 79 31

Note that the “Ar[,,1]” statement runs just fine when the data has been transferred via two for loops. It may be far more code, but it gets the job done without resulting in an error message.

Scroll to top
Privacy Policy