我想获取给定向量、矩阵或数组的每个维度的名称。像这样的东西:
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"
到目前为止,一切都很好。如果维度没有任何名称,则应返回 NULL:
b = c(1:5)
dimnames(b)
# NULL
也能正常工作。但是,当我这样做时:
a2 = matrix(1, nrow=2, ncol=2)
dimnames(a2)
# NULL
即使有两个轴名称分别为NULL
,这也会给出NULL
。因此我预计结果是:
# [[1]]
# NULL
# [[2]]
# NULL
而不是由dimnames()
给出的。
有什么办法可以做到这一点吗?
最佳答案
我认为基本 R 中没有内置任何内容。但是编写您自己的内容相当容易:
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))
关于r - 获取实际的 dimnames() 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21582619/