[R] Extracting the dimnames of an array with variable dimensions

Dennis Murphy djmuser at gmail.com
Mon May 16 07:14:07 CEST 2011


Hi:

Does it have to be an array?  If all you're interested in is the
dimnames, how about this?

library(plyr)
foo <- array(data = rnorm(32), dim = c(4,4,2),
                   dimnames=list(letters[1:4], LETTERS[1:4], letters[5:6]))
> foo
, , e

           A          B          C          D
a -0.2183877 -0.8912908 -2.0175612 -0.8080548
b  0.4870784 -0.8626293 -0.5641368 -0.5219722
c  0.8821044  0.3187850  1.2203297 -0.3151186
d -0.9894656 -1.1779108  0.9853935  0.3560747

, , f

           A          B          C          D
a  0.7357773 -1.7591637  1.6320887  1.2248529
b  0.4662315  0.1131432 -0.9790887 -0.6575306
c -0.3564725 -0.9202688  0.1017894  0.7382683
d  0.2825117  0.9242299  0.3577063 -1.3297339

# flatten array into a data frame with dimnames as factors
# adply() converts an array to a data frame, applying a function
# along the stated dimensions
 u <- adply(foo, c(1, 2, 3), as.vector)
subset(u, V1 > 0)[, 1:3]
   X1 X2 X3
2   b  A  e
3   c  A  e
7   c  B  e
11  c  C  e
12  d  C  e
16  d  D  e
17  a  A  f
18  b  A  f
20  d  A  f
22  b  B  f
24  d  B  f
25  a  C  f
27  c  C  f
28  d  C  f
29  a  D  f
31  c  D  f

HTH,
Dennis

On Sun, May 15, 2011 at 9:20 PM, Pierre Roudier
<pierre.roudier at gmail.com> wrote:
> Hi list,
>
> In a function I am writing, I need to extract the dimension names of
> an array. I know this can be acheived easily using dimnames() but my
> problem is that I want my function to be robust when the number of
> dimensions varies. Consider the following case:
>
> foo <- array(data = rnorm(32), dim = c(4,4,2),
> dimnames=list(letters[1:4], LETTERS[1:4], letters[5:6]))
>
> # What I want is to extract the *names of the dimensions* for which
> foo have positive values:
> ind <- which(foo > 0, arr.ind = TRUE)
>
> # A first solution is:
> t(apply(ind, 1, function(x) unlist(dimnames(foo[x[1], x[2], x[3],
> drop=FALSE]))))
> # But it does require to know the dimensions of foo
>
> I would like to do something like:
>
> ind <- which(foo > 0, arr.ind = TRUE)
> t(apply(ind, 1, function(x) unlist(dimnames(foo[x, drop=FALSE]))))
>
> but in that case the dimnames are dropped.
>
> Any suggestion?
>
> Cheers,
>
> Pierre
>
> --
> Scientist
> Landcare Research, New Zealand
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list