I am trying to create a function that given m and p returns a matrix with m rows and mxp columns. The matrix should have 0's except for p positions, starting at p (number of row).
For example, given m=4 and p=2, the matrix should look like:
1 1 0 0 0 0 0 0
0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0
0 0 0 0 0 0 1 1
I want to work with big matrices.
I know how to do this with loops in other programming languages such as python, but I am sure that it should be an easier and more elegant way to do this in R. I have been playing for a while with diag() without finding the solution.
apply()ing the rep() function to each row (or column, it's the same) of the diagonal matrix:
t(apply(diag(m), 2, rep, each = p))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# [1,] 1 1 0 0 0 0 0 0
# [2,] 0 0 1 1 0 0 0 0
# [3,] 0 0 0 0 1 1 0 0
# [4,] 0 0 0 0 0 0 1 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With