1

我想替换列表中包含的矩阵的对角元素。

w <- matrix(rnorm(25), 5)
t <- matrix(seq(1, 25, 1), 5)
s <- list(w, t)

如果我尝试这个,它会起作用。

diag(s[[1]]) <- rep(0, 5)
diag(s[[2]]) <- rep(0,5)

但是如果我尝试这个,我会收到一条错误消息。

lapply(1:2, function(i){diag(s[[i]]) <- rep(0, nrow(s[[i]]))})

所以有两件事是错误的。首先是“lapply-loop”。第二个是nrow(s[[i]])。但为什么。我不明白这一点。谢谢。

4

2 回答 2

4

这应该工作

lapply(s, function(x) { diag(x) <- 0; x})

这相当于

lapply(s, function(x) {
  diag(x) <- 0
  return(x)})

请注意,这是有效的,因为匿名函数有一个要返回的对象,它在之后;或明确指出return(x)

于 2013-11-13T20:29:40.813 回答
1

我会用mapply. 当您的对角线依赖于另一个变量时,此方法将是合适的。

mapply(FUN = function(i, s) {
  diag(s) <- 0 # zero recycles, see Jilber's answer
  s
}, as.list(1:2), s, SIMPLIFY = FALSE)

[[1]]
          [,1]       [,2]       [,3]       [,4]       [,5]
[1,] 0.0000000 -1.7904313  1.3729230 -2.9166446  0.8452616
[2,] 0.4426715  0.0000000  0.6949080  0.7575147 -0.1733760
[3,] 1.1239462 -0.4743851  0.0000000  0.7562622  0.9003581
[4,] 1.0866904 -0.1133565 -0.1176390  0.0000000 -0.7320746
[5,] 0.4296460 -1.0967132 -0.9295789 -1.9490995  0.0000000

[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    6   11   16   21
[2,]    2    0   12   17   22
[3,]    3    8    0   18   23
[4,]    4    9   14    0   24
[5,]    5   10   15   20    0
于 2013-11-13T21:03:54.610 回答