[R] the real dimnames

Michael Lachmann lachmann at eva.mpg.de
Mon Jul 26 20:01:57 CEST 2010


Hi,

R seems to have a feature that isn't used much, which I don't really  
now how to call. But, the dimnames function, can in addition to giving  
names to rows/columns/dim 3 rows/dim 4 rows... can also give labels to  
the dimensions themselves.

Thus, I can do:
A = matrix(1:9,3,3)

dimnames(A) = list(from=c(), to=c() )

and now, printing a prints these dimension labels nicely:
 > A
       to
from   [,1] [,2] [,3]
   [1,]    1    4    7
   [2,]    2    5    8
   [3,]    3    6    9

I don't know exactly what these labels are called, but they can be  
handy sometimes.
For example, they could be handy when using aperm. Instead of writing

aperm(A, c(2,1) )

It would be nice to be able to write:

aperm(A, c("from","to") )

This way, I don't have to remember what is the order of the dims of A.

It is easy to extend the functionality of aperm, so that the above  
code works:
---
my.aperm=function( A, d , ...) {
   n=names(dimnames(A))
   if( is.null(n) ) {
     return( aperm(A,d, ...))
   }

   dimnum = seq(along=n)
   names(dimnum) = n

   return( aperm(A, dimnum[d], ... ))
}
--

It seems some functions support these dim labels (print, for example),  
and some don't (for example, matrix multiplication doesn't, aperm  
doesn't, apply doesn't).

Another cool way to use these, would be labeled arguments in array  
subsetting:
 > a[to=1:2,from=2:3]
       to
from   [,1] [,2]
   [1,]    4    7
   [2,]    5    8
 > a[from=1:2,to=2:3]
       to
from   [,1] [,2]
   [1,]    4    7
   [2,]    5    8

No, doesn't seem to work.

My questions are:
1. Do these have names, so that I can search the documentation for them?
2. How are they usually used?

thanks,
Michael



More information about the R-help mailing list