在矩阵列表上递归设置dimnames

时间:2014-08-01 16:17:23

标签: r

在矩阵列表中,我只想设置colnames并将rownames保留为NULL。矩阵都是不同的维度。与此示例不同,名称特定于每个矩阵。

provideDimnames让我陷入困境,但我无法告诉它忽略NULL行名称,只设置列名。这是我的尝试。

> L <- list(matrix(1:6, 2), matrix(1:20, 5))
> dimnm <- list(list(NULL, letters[1:3]), list(NULL, letters[1:4]))
> lapply(L, provideDimnames, base = dimnm)
# Error in make.unique(base[[ii]][1L + (ss%%M[ii])], sep = sep) : 
#     'names' must be a character vector
> lapply(L, provideDimnames, base = list(dimnm))
# Error in make.unique(base[[ii]][1L + (ss%%M[ii])], sep = sep) : 
#     'names' must be a character vector
> lapply(L, provideDimnames, base = list(letters))
# [[1]]
#   a b c
# a 1 3 5
# b 2 4 6
# 
# [[2]]
#   a  b  c  d
# a 1  6 11 16
# b 2  7 12 17
# c 3  8 13 18
# d 4  9 14 19
# e 5 10 15 20

差不多,但我希望[n,]代表行名称。期望的结果是:

> dimnames(L[[1]]) <- list(NULL, letters[1:3])
> dimnames(L[[2]]) <- list(NULL, letters[1:4])
> L
# [[1]]
#      a b c
# [1,] 1 3 5
# [2,] 2 4 6
# 
# [[2]]
#      a  b  c  d
# [1,] 1  6 11 16
# [2,] 2  7 12 17
# [3,] 3  8 13 18
# [4,] 4  9 14 19
# [5,] 5 10 15 20

> lapply(L, provideDimnames, base = list(NULL, letters))
# Error in make.unique(base[[ii]][1L + (ss%%M[ii])], sep = sep) : 
#     'names' must be a character vector
> lapply(L, `colnames<-`, , letters)
# Error in FUN(X[[1L]], ...) : 
#   unused argument (c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
#   "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"))

有没有办法用provideDimnames()执行此操作? setNames()也不会接受昏暗名称的列表。

2 个答案:

答案 0 :(得分:4)

这样的事情怎么样?

L <- list(matrix(1:6, 2), matrix(1:20, 5))
nms <- list(letters[1:3], letters[23:26])

mapply(function(X,Y) {colnames(X) <-Y; X}, L, nms)
[[1]]
     a b c
[1,] 1 3 5
[2,] 2 4 6

[[2]]
     w  x  y  z
[1,] 1  6 11 16
[2,] 2  7 12 17
[3,] 3  8 13 18
[4,] 4  9 14 19
[5,] 5 10 15 20

答案 1 :(得分:3)

你可以相对容易地做到这一点,但是你要通过尝试同时做两个dimnames来实现这一点,你真的只想摆弄列名。我会这样做:

## different dimnames; list of only the colnames
dimnm <- list(letters[1:3], letters[1:4])

## function to lapply which does the change
cnames <- function(i, lmat, names) {
  colnames(lmat[[i]]) <- names[[i]]
  lmat[[i]]
}

## do the change
L2 <- lapply(seq_along(L), cnames, lmat = L, names = dimnm)
L2

给我们:

> L2
[[1]]
     a b c
[1,] 1 3 5
[2,] 2 4 6

[[2]]
     a  b  c  d
[1,] 1  6 11 16
[2,] 2  7 12 17
[3,] 3  8 13 18
[4,] 4  9 14 19
[5,] 5 10 15 20