I have a vector of n numbers, for simplicity assume that
test <- c(1:100)
It is simple to construct a diagonal matrix for a vector with diag().
However, I want to extract every value of the vector and create a 4x4 matrix with the extracted value being in i = 1 and j = 1 (upper left hand corner) and all other values being zero.
Personally, I have no clue whatsoever how to accomplish that.
Why do I want to do that? I'm performing Input/Output analysis and want to calculate the inoperability of a sector. For that I need the sector recovery time which is in a vector of 1000 randomly generated recovery times from a pert distribution.
To be more precise:
If I have this vector from 1:100 I want to extract every value from 1:100 and create a separate matrix that looks like this (for 1 to 100):
1 0 0 0
0 0 0 0
0 0 0 0
CodePudding user response:
A slightly shorter version would be
lapply(1:100, function(x) matrix(c(x, rep(0, 15)), 4))
CodePudding user response:
lapply(1:100, \(z) {
m <- matrix(0, nrow = 4, ncol = 4);
m[1,1] <- z;
m})
if possible sparse matrices, could be more memory efficient:
lapply(1:100, \(z) {
Matrix::sparseMatrix(1, 1, x = z, dims = c(4,4))
})
CodePudding user response:
Another option would be to use a 3D array:
test <- 1:100
nr <- 3L
nc <- 4L
a <- array(0L, c(3, 4, length(test)))
a[1,1,] <- test
a[,,1]
#> [,1] [,2] [,3] [,4]
#> [1,] 1 0 0 0
#> [2,] 0 0 0 0
#> [3,] 0 0 0 0
a[,,12]
#> [,1] [,2] [,3] [,4]
#> [1,] 12 0 0 0
#> [2,] 0 0 0 0
#> [3,] 0 0 0 0