R:如何将矩阵每一行中的条目加倍并插入新行

R: how to double the entries in each row of a matrix and insert new rows

mylist <- list(matrix(c(1, 3, -1, 0, 2, 1), nrow = 2, byrow = TRUE),
               matrix(c(-2, 0, 10, 1, 2, 9, 2, 0, 0), nrow = 3, byrow = TRUE))
> mylist
[[1]]
     [,1] [,2] [,3]
[1,]    1    3   -1
[2,]    0    2    1

[[2]]
     [,1] [,2] [,3]
[1,]   -2    0   10
[2,]    1    2    9
[3,]    2    0    0

我有一个名为 mylist 的矩阵列表,其中矩阵的维度可以不同。对于每个矩阵,我想将行值加倍并将其作为新行插入下方。我想要的输出如下:

[[1]]
     [,1] [,2] [,3]
[1,]    1    3   -1
[2,]    2    6   -2
[3,]    0    2    1
[4,]    0    4    2

[[2]]
     [,1] [,2] [,3]
[1,]   -2    0   10
[2,]   -4    0   20
[3,]    1    2    9
[4,]    2    4   18
[5,]    2    0    0
[6,]    4    0    0

您可以使用 rbind,但您需要排列行以获得下方的乘积行:

lapply(
  mylist,
  function(x){
    rbind(x, x * 2)[as.vector(t(matrix(seq_len(nrow(x) * 2), ncol = 2))),]
  }     
)

[[1]]
     [,1] [,2] [,3]
[1,]    1    3   -1
[2,]    2    6   -2
[3,]    0    2    1
[4,]    0    4    2

[[2]]
     [,1] [,2] [,3]
[1,]   -2    0   10
[2,]   -4    0   20
[3,]    1    2    9
[4,]    2    4   18
[5,]    2    0    0
[6,]    4    0    0

lapply rep 吃掉使用 seq_lennrow 找到的每一行索引并重复乘以 1:2 利用回收。

lapply(mylist, \(x) x[rep(seq_len(nrow(x)), each=2), ]*1:2)
# [[1]]
#      [,1] [,2] [,3]
# [1,]    1    3   -1
# [2,]    2    6   -2
# [3,]    0    2    1
# [4,]    0    4    2
# 
# [[2]]
#      [,1] [,2] [,3]
# [1,]   -2    0   10
# [2,]   -4    0   20
# [3,]    1    2    9
# [4,]    2    4   18
# [5,]    2    0    0
# [6,]    4    0    0

另一种基础 R 方法,它也使用 rbind 函数和 do.call

lapply(mylist, function(x) 
  do.call(rbind, lapply(1:nrow(x), function(i) rbind(x[i, ], x[i,]*2))))

[[1]]
     [,1] [,2] [,3]
[1,]    1    3   -1
[2,]    2    6   -2
[3,]    0    2    1
[4,]    0    4    2

[[2]]
     [,1] [,2] [,3]
[1,]   -2    0   10
[2,]   -4    0   20
[3,]    1    2    9
[4,]    2    4   18
[5,]    2    0    0
[6,]    4    0    0