Reputation: 56915
I've been writing a number of functions on arrays in R that are of an image-processing type.
What this means is that the functions operate on:
The thing is, greyscale images are 2-dimensional: dim(ary)
is c(n,m)
.
By contrast, colour images are 3-dimensional: dim(ary)
is c(n,m,3)
.
At the moment my functions all have something like (following example is contrived but demonstrates my problem):
f <- function(img)
{
if ( length(dim(img)) == 2 )
return( img[1:10,] )
else
return( img[1:10,,] ) # Note the extra comma to select all 3D slices?
}
That is, I always have to include a check to say "if it's a two-dimensional array then don't put in the extra comma that indicates "everything in the third dimension"".
Is there some way I can get around this? Since a 2-dimensional array is really a 3-dimensional array with dim(ary) = c(n,m,1)
, it'd be great to use the same subsetting syntax for both.
Is there some way I can tell R "if I add in one too many commas in the indexing, you should assume that is a singleton dimension" ?
(I suppose I could do the reshaping myself via dim(img) <- c(dim(img),1)
, but that still requires me to check that length(dim(img))==2
and I'd like know if there's away to avoid this check at the start of every function.
Upvotes: 2
Views: 263
Reputation: 897
One approach would be to put a class on your objects -- either grey or colour -- and then the subscripting function for 'grey' objects can just ignore the last dimension. The [
method for the colour objects need not even exist.
Upvotes: 1