# Re: [Rd] Using 'dimname names' in aperm() and apply()

From: ghostwheel <lachmann_at_eva.mpg.de>
Date: Fri, 20 Apr 2012 08:50:24 -0700 (PDT)

I think the dimnames facility is underused in R. I'm currently using a 5-dimensional array. It is quite cumbersome to have to write
y[,,,,"0"]

Since the array does have dimnames, I would like to be able to say instead y[tree="0"]

Below is a function that enables this functionality
--

myslice=function( input.array,...){
args=list(...)
if( length(names(args))==0 ) {
d = args
} else {
d=dimnames( input.array )
for(n in names(args)) {

```      i=args[[n]]
if( is.numeric(i)) {
if( length(d[[n]]) == 0) d[[n]]=i
else d[[n]]=d[[n]][i]
} else d[[n]]=args[[n]]
```

}
}
dd=dim( input.array )
for(i in seq(along=dd))
if( length(d[[i]])==0) d[[i]] = seq( dd[i])   i=sapply(d,length)>1
new.dimnames=dimnames(input.array)[i]
d=c(list( input.array ),d)
ret = do.call("[",d)
dimnames(ret) = new.dimnames
ret
}
---

I'm not sure what is the best way to replace "[" for arrays with this function. I should also implement [<- in the same manner.

One additional feature of this function is that it keeps dimnames. So, if we have
A=array(1:24,c(2,3,4),dimnames=list(a=c(),b=c(),c=c())) (btw, why can't I do A=array(1:24,c(a=2,b=3,c=4))?)

Then A[1,,] will give a matrix without dimnames:
--

> A[1,,]

[,1] [,2] [,3] [,4]

```[1,]    1    7   13   19
[2,]    3    9   15   21
[3,]    5   11   17   23
```

--

Whereas the new function keeps the dimnames:
--

> myslice(A,a=1)
```      c
b      [,1] [,2] [,3] [,4]
[1,]    1    7   13   19
```

[2,] 3 9 15 21
[3,] 5 11 17 23
--

Another function where using dimnames for MARGIN would be slice.index

Thanks!
Michael

--

View this message in context: http://r.789695.n4.nabble.com/Using-dimname-names-in-aperm-and-apply-tp2307013p4574463.html Sent from the R devel mailing list archive at Nabble.com.

R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Fri 20 Apr 2012 - 15:59:50 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 21 Apr 2012 - 01:00:48 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.