For a vector, I would like to create a square matrix in which the elements of the vector are located diagonally, and there is a line with the outline of the elements.
Vector example:
vec <- c(1, 2, 3, 4)
Required Conclusion:
[,1] [,2] [,3] [,4] [1,] 1 3 6 10 [2,] 0 2 5 9 [3,] 0 0 3 7 [4,] 0 0 0 4
Now I use the double function for the loop:
diagSum <- function(vec) { mat <- diag(vec) for (i in seq(nrow(mat))) { for (j in seq(i, ncol(mat))) { if (j > i) { mat[i, j] <- mat[i, j - 1] + mat[j, j] } } } mat }
What will the R-way (avoiding for loops) do this?
source share