# Re: [R] Correct way to test for exact dimensions of matrix or array

From: Martin Maechler <maechler_at_stat.math.ethz.ch>
Date: Wed 11 Jan 2006 - 02:13:30 EST

>>>>> "Gregory" == Gregory Jefferis <gsxej2@cam.ac.uk> >>>>> on Tue, 10 Jan 2006 14:47:43 +0000 writes:

```     Gregory> I want to test the dimensions of an incoming
Gregory> vector, matrix or array safely

Gregory> and succinctly.  Specifically I want to check if
```
Gregory> the unknown object has exactly 2 dimensions with a     Gregory> specified number of rows and columns.

Gregory> I thought that the following would work:

>> obj=matrix(1,nrow=3,ncol=5)
>> identical( dim( obj) , c(3,5) )
Gregory> [1] FALSE

Gregory> OR

>> isTRUE(all( dim( obj) == c(3,5) ))

But, you say that it's part of your function checking it's arguments.
In that case, I'd recommend

```     if(length(d <- dim(obj)) != 2)
stop("'d' must be matrix-like")
if(!all(d == c(3,5)))
stop("the matrix must be  3 x 5")

```

which also provides for nice error messages in case of error. A more concise form with less nice error messages is

stopifnot(length(d <- dim(obj)) == 2,

d == c(3,50))

## you can leave away all(.) for things in stopifnot(.)

Gregory> Neither of which feel quite right. Is there a 'correct' way to do this?

Gregory> Many thanks,

You're welcome,
Martin Maechler, ETH Zurich

Gregory> Greg Jefferis.

>> obj=array(1,dim=c(3,5,3,5))
>> isTRUE(all( dim( obj) == c(3,5) ))
Gregory> [1] TRUE

Gregory> OR
>> obj=numeric(10)
>> isTRUE(all( dim( obj) == c(3,5) ))
Gregory> [1] TRUE

R-help@stat.math.ethz.ch mailing list