How to move rows horizontal on matrix depending on the value

Viewed 31

I currently have two matrix:

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

and

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

it is possible to move rows automatically horizontal to the right by step of number on first matrix and all empty site complete 0? The result will be like that:

      [,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
1 Answers

You can use mapply() with 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

Data
mat1 <- matrix(c(0, 5, 1))
mat2 <- matrix(c(0, 0, 1, 0, 9, 1, 1, 9, 1), 3)
Related