I'd like to get the names of each dimension for a given vector, matrix, or array. Something like:

a = matrix(1, nrow=2, ncol=2, dimnames=list(c('a','b'),c('x','y')))

dimnames(a)
# [[1]]
# [1] "a" "b"
#
# [[2]]
# [1] "x" "y"

So far, so good. If a dimension doesn't have any names, it should return NULL:

b = c(1:5)

dimnames(b)
# NULL

Also works fine. However, when I do:

a2 = matrix(1, nrow=2, ncol=2)

dimnames(a2)
# NULL

This gives NULL, even though there are two axes names which are each NULL. Hence I would expect the result to be:

# [[1]]
# NULL
# [[2]]
# NULL

instead of the one given by dimnames().

Is there any way to do that?

有帮助吗?

解决方案

I don't think there's anything built into base R. But it's fairly easy to write your own:

dimnames2 <- function(x) {
  if (is.vector(x)) {
    list(names(x))
  } else {
    d <- dimnames(x)
    if (is.null(d)) {
      rep(list(NULL), length(dim(x)))
    } else {
      d
    }
  }
}

dimnames2(1:10)
dimnames2(matrix(1:10))

其他提示

Here’s a one-liner to do essentially what Hadley is doing (independently derived, I swear ;-)):

> dimnames2 = function (x) dimnames(x) %else% rep(list(NULL), length(dim(x)))
> dimnames2(a)
[[1]]
[1] "a" "b"

[[2]]
[1] "x" "y"
> dimnames2(a2)
[[1]]
NULL

[[2]]
NULL

Oh yeah, I cheated. %else% is equivalent to the null-coalesce operator in C#, or or in Perl, Ruby, PHP …:

`%else%` = function (a, b) if (identical(a, FALSE) || is.null(a) || length(a) == 0) b else a
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top