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

Pierre Roudier pierre.roudier at gmail.com
Mon May 16 06:20:30 CEST 2011


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



More information about the R-help mailing list