如何根据值在矩阵上水平移动行

How to move rows horizontal on matrix depending on the value

我目前有两个矩阵:

      [,1]
[1,]    0
[2,]    5
[3,]    1

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

是否可以在第一个矩阵上按数字步长自动水平向右移动行,并且所有空位全部为 0?结果将是这样的:

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    0    0    1    0    0    0    0    0
[2,]    0    0    0    0    0    0    9    9
[3,]    0    1    1    1    0    0    0    0

您可以将 mapply()append() 一起使用:

t(mapply(append, asplit(mat2, 1), mat1,
         MoreArgs = list(x = rep(0, max(mat1)))))

#      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# [1,]    0    0    1    0    0    0    0    0
# [2,]    0    0    0    0    0    0    9    9
# [3,]    0    1    1    1    0    0    0    0

数据
mat1 <- matrix(c(0, 5, 1))
mat2 <- matrix(c(0, 0, 1, 0, 9, 1, 1, 9, 1), 3)