Insert a number above the diagonal into the matrix R

I have such a vector in R:

vec1 <- c(14000,12000,8000) 

I'm trying to create a matrix, where 14000 is my main diagonal, 1200 is one above the diagonal, 8000 is two above the diagonal.

I am familiar with this in Python / numpy, but cannot figure it out in R (or at least an efficient way to do this). Ideally, the output would look like this:

 14000 12000 8000 0 14000 12000 0 0 14000 
+6
source share
2 answers

Try

 m1 <- t(matrix(vec1, nrow=5, ncol=3))[,1:3] m1[lower.tri(m1)] <- 0 m1 # [,1] [,2] [,3] #[1,] 14000 12000 8000 #[2,] 0 14000 12000 #[3,] 0 0 14000 

or use toeplitz

 toeplitz(vec1)*upper.tri(diag(seq_along(vec1)), diag=TRUE) # [,1] [,2] [,3] #[1,] 14000 12000 8000 #[2,] 0 14000 12000 #[3,] 0 0 14000 

Or a modification proposed by @David Arenburg

 m <- toeplitz(vec1) m[lower.tri(m)] <- 0 
+6
source

In this simple case, you can separately assign the diagonal and upper triangular parts as follows:

 m <- matrix(0, nrow=3, ncol=3) diag(m) <- 14000 m[upper.tri(m)] <- c(12000, 8000, 12000) 

However, as David Arenburg pointed out, this is a more manual approach and therefore does not scale very well. For a more automated, scalable approach, I recommend the akrun solution with toeplitz() and lower.tri() .

I will keep this answer here for completeness in your particular case, but I think that acrun is the best overall solution.

+1
source

Source: https://habr.com/ru/post/985806/


All Articles