[Rd] Using 'dimname names' in aperm() and apply()
ghostwheel
lachmann at eva.mpg.de
Fri Apr 20 17:50:24 CEST 2012
I'm replying here to quite an old thread started by me.
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.
More information about the R-devel
mailing list